libbin 1.0.8 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,13 +3,27 @@
3
3
 
4
4
  VALUE cField;
5
5
  VALUE mLibBin;
6
- VALUE cDataConverter;
7
-
8
- static VALUE rb_str_dot_dot;
6
+ VALUE cStructure;
7
+ VALUE eLibBinError;
8
+ VALUE eLibBinEOFError;
9
+ VALUE eLibBinValidationError;
10
+ VALUE eLibBinAlignmentError;
11
+ static VALUE cStructure_sclass;
12
+
13
+ static VALUE rb_re_dot_dot;
9
14
  static VALUE rb_str___parent;
10
15
  static VALUE rb_str_backslash;
11
16
  static VALUE rb_str_dot;
12
17
 
18
+ static ID id_ivar_structure;
19
+ static ID id_ivar_field;
20
+ static ID id_ivar_offset;
21
+ static ID id_ivar_index;
22
+
23
+ #ifdef HAVE_RB_RACTOR_LOCAL_STORAGE_VALUE_NEWKEY
24
+ static rb_ractor_local_key_t libbin_ractor_flags_key;
25
+ #endif
26
+
13
27
  struct cField_data {
14
28
  VALUE name;
15
29
  VALUE type;
@@ -19,15 +33,49 @@ struct cField_data {
19
33
  VALUE sequence;
20
34
  VALUE condition;
21
35
  VALUE relative_offset;
36
+ VALUE align;
37
+ VALUE expect;
38
+ VALUE null_offset;
39
+ /* non-VALUE fields below; cField_mark / cField_compact cover all VALUEs above */
22
40
  ID getter;
23
41
  ID setter;
42
+ ID ivar;
43
+ uint8_t scalar_kind;
44
+ uint8_t is_static_simple;
45
+ uint8_t type_is_struct;
24
46
  };
25
47
 
26
48
  static void cField_mark(void* data) {
27
- void *start = data;
28
- void *end = &((struct cField_data*)data)->getter;
29
- rb_gc_mark_locations((VALUE *)start, (VALUE *)end);
30
- }
49
+ struct cField_data *d = (struct cField_data *)data;
50
+ LIBBIN_GC_MARK(d->name);
51
+ LIBBIN_GC_MARK(d->type);
52
+ LIBBIN_GC_MARK(d->length);
53
+ LIBBIN_GC_MARK(d->count);
54
+ LIBBIN_GC_MARK(d->offset);
55
+ LIBBIN_GC_MARK(d->sequence);
56
+ LIBBIN_GC_MARK(d->condition);
57
+ LIBBIN_GC_MARK(d->relative_offset);
58
+ LIBBIN_GC_MARK(d->align);
59
+ LIBBIN_GC_MARK(d->expect);
60
+ LIBBIN_GC_MARK(d->null_offset);
61
+ }
62
+
63
+ #ifdef HAVE_RB_GC_LOCATION
64
+ static void cField_compact(void* data) {
65
+ struct cField_data *d = (struct cField_data *)data;
66
+ d->name = rb_gc_location(d->name);
67
+ d->type = rb_gc_location(d->type);
68
+ d->length = rb_gc_location(d->length);
69
+ d->count = rb_gc_location(d->count);
70
+ d->offset = rb_gc_location(d->offset);
71
+ d->sequence = rb_gc_location(d->sequence);
72
+ d->condition = rb_gc_location(d->condition);
73
+ d->relative_offset = rb_gc_location(d->relative_offset);
74
+ d->align = rb_gc_location(d->align);
75
+ d->expect = rb_gc_location(d->expect);
76
+ d->null_offset = rb_gc_location(d->null_offset);
77
+ }
78
+ #endif
31
79
 
32
80
  static size_t cField_size(const void* data) {
33
81
  (void)data;
@@ -40,9 +88,15 @@ static const rb_data_type_t cField_type = {
40
88
  .dmark = cField_mark,
41
89
  .dfree = RUBY_DEFAULT_FREE,
42
90
  .dsize = cField_size,
91
+ #ifdef HAVE_RB_GC_LOCATION
92
+ .dcompact = cField_compact,
93
+ #endif
43
94
  },
44
95
  .data = NULL,
45
96
  .flags = RUBY_TYPED_FREE_IMMEDIATELY
97
+ #ifdef RUBY_TYPED_FROZEN_SHAREABLE
98
+ | RUBY_TYPED_FROZEN_SHAREABLE
99
+ #endif
46
100
  };
47
101
 
48
102
  static VALUE cField_alloc(VALUE self) {
@@ -52,13 +106,28 @@ static VALUE cField_alloc(VALUE self) {
52
106
  }
53
107
 
54
108
  static ID id_gsub;
109
+ static ID id_eval;
110
+ static VALUE rb_field_eval_binding;
55
111
 
56
- static inline VALUE cField_preprocess_expression(VALUE self, VALUE expression) {
112
+ #ifdef HAVE_RB_RACTOR_MAKE_SHAREABLE
113
+ static VALUE cField_protect_make_shareable(VALUE obj) {
114
+ return rb_ractor_make_shareable(obj);
115
+ }
116
+ #endif
117
+
118
+ static inline VALUE cField_preprocess_expression(VALUE expression) {
57
119
  if (T_STRING == TYPE(expression)) {
58
120
  VALUE proc = rb_str_new_cstr("proc {");
59
- rb_str_buf_append(proc, rb_funcall(rb_funcall(expression, id_gsub, 2, rb_str_dot_dot, rb_str___parent), id_gsub, 2, rb_str_backslash, rb_str_dot));
121
+ rb_str_buf_append(proc, rb_funcall(rb_funcall(expression, id_gsub, 2, rb_re_dot_dot, rb_str___parent), id_gsub, 2, rb_str_backslash, rb_str_dot));
60
122
  rb_str_cat_cstr(proc, "}");
61
- return rb_obj_instance_eval(1, &proc, self);
123
+ VALUE res = rb_funcall(rb_mKernel, id_eval, 2, proc, rb_field_eval_binding);
124
+ #ifdef HAVE_RB_RACTOR_MAKE_SHAREABLE
125
+ int state = 0;
126
+ rb_protect(cField_protect_make_shareable, res, &state);
127
+ if (state)
128
+ rb_set_errinfo(Qnil);
129
+ #endif
130
+ return res;
62
131
  } else
63
132
  return expression;
64
133
  }
@@ -72,101 +141,100 @@ static VALUE cField_initialize(
72
141
  VALUE offset,
73
142
  VALUE sequence,
74
143
  VALUE condition,
75
- VALUE relative_offset) {
76
- VALUE tmp;
144
+ VALUE relative_offset,
145
+ VALUE align,
146
+ VALUE expect,
147
+ VALUE null_offset) {
77
148
  struct cField_data *data;
78
149
  TypedData_Get_Struct(self, struct cField_data, &cField_type, data);
150
+ if (RTEST(align)) {
151
+ long long a = NUM2LL(align);
152
+ if (a <= 0 || (a & (a - 1)))
153
+ rb_raise(eLibBinAlignmentError, "alignment is not a power of 2: %lld", a);
154
+ }
155
+ if (RTEST(null_offset))
156
+ (void)NUM2LL(null_offset);
79
157
  data->name = name;
80
- tmp = rb_str_dup(rb_obj_as_string(name));
81
- data->getter = rb_intern_str(tmp);
82
- data->setter = rb_intern_str(rb_str_cat(tmp, "=", 1));
83
- data->type = cField_preprocess_expression(self, type);
84
- data->length = cField_preprocess_expression(self, length);
85
- data->count = cField_preprocess_expression(self, count);
86
- data->offset = cField_preprocess_expression(self, offset);
158
+ if (NIL_P(name)) {
159
+ data->getter = 0;
160
+ data->setter = 0;
161
+ data->ivar = 0;
162
+ } else {
163
+ VALUE tmp = rb_str_dup(rb_obj_as_string(name));
164
+ data->getter = rb_intern_str(tmp);
165
+ VALUE ivar_str = rb_str_new_cstr("@");
166
+ rb_str_buf_append(ivar_str, tmp);
167
+ data->ivar = rb_intern_str(ivar_str);
168
+ data->setter = rb_intern_str(rb_str_cat(tmp, "=", 1));
169
+ }
170
+ data->type = cField_preprocess_expression(type);
171
+ data->length = cField_preprocess_expression(length);
172
+ data->count = cField_preprocess_expression(count);
173
+ data->offset = cField_preprocess_expression(offset);
87
174
  data->sequence = sequence;
88
- data->condition = cField_preprocess_expression(self, condition);
175
+ data->condition = cField_preprocess_expression(condition);
89
176
  data->relative_offset = relative_offset;
177
+ data->align = align;
178
+ data->expect = expect;
179
+ data->null_offset = null_offset;
180
+ data->scalar_kind = (uint8_t)libbin_lookup_scalar_kind(data->type);
181
+ data->type_is_struct = (RB_TYPE_P(data->type, T_CLASS) && RTEST(rb_class_inherited_p(data->type, cStructure))) ? 1 : 0;
182
+ data->is_static_simple = (
183
+ !RTEST(data->sequence) &&
184
+ !RTEST(data->condition) &&
185
+ !RTEST(data->offset) &&
186
+ !RTEST(data->align) &&
187
+ !RTEST(data->count) &&
188
+ NIL_P(data->expect) &&
189
+ !rb_obj_is_proc(data->type) &&
190
+ !rb_obj_is_proc(data->length)
191
+ ) ? 1 : 0;
192
+ #if defined(HAVE_RB_RACTOR_SHAREABLE_P) && defined(HAVE_RB_RACTOR_MAKE_SHAREABLE)
193
+ if (rb_ractor_shareable_p(data->name) &&
194
+ rb_ractor_shareable_p(data->type) &&
195
+ rb_ractor_shareable_p(data->length) &&
196
+ rb_ractor_shareable_p(data->count) &&
197
+ rb_ractor_shareable_p(data->offset) &&
198
+ rb_ractor_shareable_p(data->sequence) &&
199
+ rb_ractor_shareable_p(data->condition) &&
200
+ rb_ractor_shareable_p(data->relative_offset) &&
201
+ rb_ractor_shareable_p(data->align) &&
202
+ rb_ractor_shareable_p(data->expect) &&
203
+ rb_ractor_shareable_p(data->null_offset)) {
204
+ rb_ractor_make_shareable(self);
205
+ }
206
+ #endif
90
207
  return self;
91
208
  }
92
209
 
93
- static VALUE cField_name(VALUE self) {
94
- struct cField_data *data;
95
- TypedData_Get_Struct(self, struct cField_data, &cField_type, data);
96
- return data->name;
97
- }
98
-
99
- static VALUE cField_get_type(VALUE self) {
100
- struct cField_data *data;
101
- TypedData_Get_Struct(self, struct cField_data, &cField_type, data);
102
- return data->type;
103
- }
104
-
105
- static VALUE cField_length(VALUE self) {
106
- struct cField_data *data;
107
- TypedData_Get_Struct(self, struct cField_data, &cField_type, data);
108
- return data->length;
109
- }
110
-
111
- static VALUE cField_count(VALUE self) {
112
- struct cField_data *data;
113
- TypedData_Get_Struct(self, struct cField_data, &cField_type, data);
114
- return data->count;
115
- }
116
-
117
- static VALUE cField_offset(VALUE self) {
118
- struct cField_data *data;
119
- TypedData_Get_Struct(self, struct cField_data, &cField_type, data);
120
- return data->offset;
121
- }
122
-
123
- static VALUE cField_sequence(VALUE self) {
124
- struct cField_data *data;
125
- TypedData_Get_Struct(self, struct cField_data, &cField_type, data);
126
- return data->sequence;
127
- }
210
+ #define FIELD_STATE_GETTER(propname) cField_get_ ## propname
128
211
 
129
- static VALUE cField_condition(VALUE self) {
130
- struct cField_data *data;
131
- TypedData_Get_Struct(self, struct cField_data, &cField_type, data);
132
- return data->condition;
212
+ #define CREATE_FIELD_STATE_GETTER(propname) \
213
+ static VALUE FIELD_STATE_GETTER(propname) (VALUE self) { \
214
+ struct cField_data *data; \
215
+ TypedData_Get_Struct(self, struct cField_data, &cField_type, data); \
216
+ return data->propname ; \
133
217
  }
134
218
 
135
- static VALUE cField_relative_offset(VALUE self) {
136
- struct cField_data *data;
137
- TypedData_Get_Struct(self, struct cField_data, &cField_type, data);
138
- return data->relative_offset;
139
- }
219
+ #define DEFINE_FIELD_STATE_GETTER(propname) \
220
+ rb_define_method(cField, #propname, FIELD_STATE_GETTER(propname), 0)
140
221
 
141
- static void define_cField() {
142
- VALUE ary = rb_ary_new_capa(4);
143
- id_gsub = rb_intern("gsub");
222
+ #define DEFINE_FIELD_STATE_GETTER_BOOL(propname) \
223
+ rb_define_method(cField, #propname "?", FIELD_STATE_GETTER(propname), 0)
144
224
 
145
- rb_str_dot_dot = rb_str_new_cstr("..");
146
- rb_ary_store(ary, 0, rb_str_dot_dot);
147
- rb_str___parent = rb_str_new_cstr("__parent");
148
- rb_ary_store(ary, 1, rb_str___parent);
149
- rb_str_backslash = rb_str_new_cstr("\\");
150
- rb_ary_store(ary, 2, rb_str_backslash);
151
- rb_str_dot = rb_str_new_cstr(".");
152
- rb_ary_store(ary, 3, rb_str_dot);
225
+ CREATE_FIELD_STATE_GETTER(name)
226
+ CREATE_FIELD_STATE_GETTER(type)
227
+ CREATE_FIELD_STATE_GETTER(length)
228
+ CREATE_FIELD_STATE_GETTER(count)
229
+ CREATE_FIELD_STATE_GETTER(offset)
230
+ CREATE_FIELD_STATE_GETTER(sequence)
231
+ CREATE_FIELD_STATE_GETTER(condition)
232
+ CREATE_FIELD_STATE_GETTER(relative_offset)
233
+ CREATE_FIELD_STATE_GETTER(align)
234
+ CREATE_FIELD_STATE_GETTER(expect)
235
+ CREATE_FIELD_STATE_GETTER(null_offset)
153
236
 
154
- cField = rb_define_class_under(mLibBin, "Field", rb_cObject);
155
- rb_define_alloc_func(cField, cField_alloc);
156
- rb_const_set(cField, rb_intern("STRINGS"), ary);
157
- rb_define_method(cField, "initialize", cField_initialize, 8);
158
- rb_define_method(cField, "name", cField_name, 0);
159
- rb_define_method(cField, "type", cField_get_type, 0);
160
- rb_define_method(cField, "length", cField_length, 0);
161
- rb_define_method(cField, "count", cField_count, 0);
162
- rb_define_method(cField, "offset", cField_offset, 0);
163
- rb_define_method(cField, "sequence", cField_sequence, 0);
164
- rb_define_method(cField, "sequence?", cField_sequence, 0);
165
- rb_define_method(cField, "condition", cField_condition, 0);
166
- rb_define_method(cField, "relative_offset?", cField_relative_offset, 0);
167
- }
168
-
169
- struct cDataConverter_data {
237
+ struct cStructure_data {
170
238
  VALUE __input;
171
239
  VALUE __output;
172
240
  VALUE __input_big;
@@ -182,39 +250,71 @@ struct cDataConverter_data {
182
250
  VALUE __length;
183
251
  VALUE __count;
184
252
  VALUE __iterator;
253
+ VALUE __value;
254
+ /* non-VALUE fields below; cStructure_mark / cStructure_compact cover all VALUEs above */
255
+ libbin_ctx_t *active_ctx;
185
256
  };
186
257
 
187
- static void cDataConverter_mark(void* data) {
188
- void *start = data;
189
- void *end = (char *)data + sizeof(struct cDataConverter_data);
190
- rb_gc_mark_locations((VALUE *)start, (VALUE *)end);
191
- }
192
-
193
- static size_t cDataConverter_size(const void* data) {
258
+ static void cStructure_mark(void* data) {
259
+ struct cStructure_data *d = (struct cStructure_data *)data;
260
+ LIBBIN_GC_MARK(d->__input);
261
+ LIBBIN_GC_MARK(d->__output);
262
+ LIBBIN_GC_MARK(d->__input_big);
263
+ LIBBIN_GC_MARK(d->__output_big);
264
+ LIBBIN_GC_MARK(d->__parent);
265
+ LIBBIN_GC_MARK(d->__index);
266
+ LIBBIN_GC_MARK(d->__position);
267
+ LIBBIN_GC_MARK(d->__cur_position);
268
+ LIBBIN_GC_MARK(d->__offset);
269
+ LIBBIN_GC_MARK(d->__condition);
270
+ LIBBIN_GC_MARK(d->__type);
271
+ LIBBIN_GC_MARK(d->__length);
272
+ LIBBIN_GC_MARK(d->__count);
273
+ LIBBIN_GC_MARK(d->__iterator);
274
+ LIBBIN_GC_MARK(d->__value);
275
+ }
276
+
277
+ #ifdef HAVE_RB_GC_LOCATION
278
+ static void cStructure_compact(void* data) {
279
+ struct cStructure_data *d = (struct cStructure_data *)data;
280
+ d->__input = rb_gc_location(d->__input);
281
+ d->__output = rb_gc_location(d->__output);
282
+ d->__input_big = rb_gc_location(d->__input_big);
283
+ d->__output_big = rb_gc_location(d->__output_big);
284
+ d->__parent = rb_gc_location(d->__parent);
285
+ d->__index = rb_gc_location(d->__index);
286
+ d->__position = rb_gc_location(d->__position);
287
+ d->__cur_position = rb_gc_location(d->__cur_position);
288
+ d->__offset = rb_gc_location(d->__offset);
289
+ d->__condition = rb_gc_location(d->__condition);
290
+ d->__type = rb_gc_location(d->__type);
291
+ d->__length = rb_gc_location(d->__length);
292
+ d->__count = rb_gc_location(d->__count);
293
+ d->__iterator = rb_gc_location(d->__iterator);
294
+ d->__value = rb_gc_location(d->__value);
295
+ }
296
+ #endif
297
+
298
+ static size_t cStructure_size(const void* data) {
194
299
  (void)data;
195
- return sizeof(struct cDataConverter_data);
300
+ return sizeof(struct cStructure_data);
196
301
  }
197
302
 
198
- static const rb_data_type_t cDataConverter_type = {
199
- .wrap_struct_name = "cDataConverter_data",
303
+ static const rb_data_type_t cStructure_type = {
304
+ .wrap_struct_name = "cStructure_data",
200
305
  .function = {
201
- .dmark = cDataConverter_mark,
306
+ .dmark = cStructure_mark,
202
307
  .dfree = RUBY_DEFAULT_FREE,
203
- .dsize = cDataConverter_size,
308
+ .dsize = cStructure_size,
309
+ #ifdef HAVE_RB_GC_LOCATION
310
+ .dcompact = cStructure_compact,
311
+ #endif
204
312
  },
205
313
  .data = NULL,
206
314
  .flags = RUBY_TYPED_FREE_IMMEDIATELY
207
315
  };
208
316
 
209
- static VALUE cDataConverter_alloc(VALUE self) {
210
- struct cDataConverter_data *data;
211
- VALUE res = TypedData_Make_Struct(self, struct cDataConverter_data, &cDataConverter_type, data);
212
- return res;
213
- }
214
-
215
- static VALUE cDataConverter_initialize(VALUE self) {
216
- struct cDataConverter_data *data;
217
- TypedData_Get_Struct(self, struct cDataConverter_data, &cDataConverter_type, data);
317
+ static inline void cStructure_init_data(struct cStructure_data *data) {
218
318
  data->__input = Qnil;
219
319
  data->__output = Qnil;
220
320
  data->__input_big = Qnil;
@@ -229,81 +329,518 @@ static VALUE cDataConverter_initialize(VALUE self) {
229
329
  data->__length = Qnil;
230
330
  data->__count = Qnil;
231
331
  data->__iterator = Qnil;
332
+ data->__value = Qnil;
333
+ data->active_ctx = NULL;
334
+ }
335
+
336
+ static VALUE cStructure_alloc(VALUE self) {
337
+ struct cStructure_data *data;
338
+ VALUE res = TypedData_Make_Struct(self, struct cStructure_data, &cStructure_type, data);
339
+ cStructure_init_data(data);
340
+ return res;
341
+ }
342
+
343
+ static VALUE cStructure_initialize(VALUE self) {
344
+ struct cStructure_data *data;
345
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
346
+ cStructure_init_data(data);
232
347
  return self;
233
348
  }
234
349
 
235
- /* attr_reader :__parent
236
- attr_reader :__index
237
- attr_reader :__iterator
238
- attr_reader :__position */
350
+ #define STRUCT_STATE_GETTER(propname) cStructure_get_ ## propname
351
+ #define STRUCT_STATE_SETTER(propname) cStructure_set_ ## propname
352
+
353
+ #define CREATE_STRUCT_STATE_ACCESSORS(propname) \
354
+ static VALUE STRUCT_STATE_GETTER(propname) (VALUE self) { \
355
+ struct cStructure_data *data; \
356
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data); \
357
+ return data->__ ## propname ; \
358
+ } \
359
+ static VALUE STRUCT_STATE_SETTER(propname) (VALUE self, VALUE propname) { \
360
+ struct cStructure_data *data; \
361
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data); \
362
+ return data->__ ## propname = propname; \
363
+ }
364
+
365
+ #define DEFINE_STRUCT_STATE_ACCESSORS(propname) \
366
+ do { \
367
+ rb_define_method(cStructure, "__" #propname, STRUCT_STATE_GETTER(propname), 0); \
368
+ rb_define_method(cStructure, "__" #propname "=", STRUCT_STATE_SETTER(propname), 1); \
369
+ } while(0)
370
+
371
+ CREATE_STRUCT_STATE_ACCESSORS(parent)
372
+ CREATE_STRUCT_STATE_ACCESSORS(index)
373
+ CREATE_STRUCT_STATE_ACCESSORS(position)
374
+ CREATE_STRUCT_STATE_ACCESSORS(cur_position)
375
+ CREATE_STRUCT_STATE_ACCESSORS(input)
376
+ CREATE_STRUCT_STATE_ACCESSORS(output)
377
+ CREATE_STRUCT_STATE_ACCESSORS(input_big)
378
+ CREATE_STRUCT_STATE_ACCESSORS(output_big)
379
+
380
+ CREATE_STRUCT_STATE_ACCESSORS(offset)
381
+ CREATE_STRUCT_STATE_ACCESSORS(condition)
382
+ CREATE_STRUCT_STATE_ACCESSORS(type)
383
+ CREATE_STRUCT_STATE_ACCESSORS(length)
384
+ CREATE_STRUCT_STATE_ACCESSORS(count)
385
+ CREATE_STRUCT_STATE_ACCESSORS(iterator)
386
+ CREATE_STRUCT_STATE_ACCESSORS(value)
387
+
388
+ /* Cached IDs */
389
+ static ID id_instance_exec;
390
+ static ID id_fields;
391
+ static ID id_last, id_values, id_compact, id_output, id_print;
392
+ static ID id_unpack, id_pack, id_first;
393
+ static ID id_initialize, id_instance_method, id_method, id_owner, id_source_location;
394
+ static ID id___libbin_flags, id___libbin_flags_gen;
395
+ static ID id_stride, id___extend_range;
396
+
397
+ static ID id___set_load_state, id___unset_load_state;
398
+ static ID id___load_field, id___load_fields, id_load, id___load;
399
+ static ID id___set_dump_state, id___unset_dump_state;
400
+ static ID id___dump_field, id___dump_fields, id_dump, id___dump;
401
+ static ID id___set_convert_state, id___unset_convert_state;
402
+ static ID id___convert_field, id___convert_fields, id_convert, id___convert;
403
+ static ID id___set_size_state, id___unset_size_state;
404
+ static ID id___shape_field, id___shape_fields, id_shape, id___shape;
405
+
406
+ /* Override detection bitmask for Structure subclasses */
407
+ #define LIBBIN_OVR_INIT (1u << 0)
408
+ #define LIBBIN_OVR_INST_LOAD (1u << 1)
409
+ #define LIBBIN_OVR_SINGL_LOAD (1u << 2)
410
+ #define LIBBIN_OVR_INST_DUMP (1u << 3)
411
+ #define LIBBIN_OVR_SINGL_DUMP (1u << 4)
412
+ #define LIBBIN_OVR_INST_CONVERT (1u << 5)
413
+ #define LIBBIN_OVR_SINGL_CONVERT (1u << 6)
414
+ #define LIBBIN_OVR_LOAD_FIELDS (1u << 7)
415
+ #define LIBBIN_OVR_DUMP_FIELDS (1u << 8)
416
+ #define LIBBIN_OVR_CONVERT_FIELDS (1u << 9)
417
+ #define LIBBIN_OVR_LOAD_FIELD (1u << 10)
418
+ #define LIBBIN_OVR_DUMP_FIELD (1u << 11)
419
+ #define LIBBIN_OVR_CONVERT_FIELD (1u << 12)
420
+ #define LIBBIN_OVR_SET_LOAD (1u << 13)
421
+ #define LIBBIN_OVR_SET_DUMP (1u << 14)
422
+ #define LIBBIN_OVR_SET_CONVERT (1u << 15)
423
+ #define LIBBIN_OVR_ACCESSORS (1u << 16)
424
+ #define LIBBIN_ALL_SCALAR_LEAF (1u << 17)
425
+ #define LIBBIN_HAS_STRIDE (1u << 18)
426
+ #define LIBBIN_HAS_OFFSET_FIELD (1u << 19)
427
+
428
+ #define LIBBIN_FAST_LOAD_MASK \
429
+ (LIBBIN_OVR_INST_LOAD | LIBBIN_OVR_SET_LOAD | LIBBIN_OVR_LOAD_FIELDS | LIBBIN_OVR_LOAD_FIELD)
430
+ #define LIBBIN_FAST_DUMP_MASK \
431
+ (LIBBIN_OVR_INST_DUMP | LIBBIN_OVR_SET_DUMP | LIBBIN_OVR_DUMP_FIELDS | LIBBIN_OVR_DUMP_FIELD)
432
+ #define LIBBIN_FAST_CONVERT_MASK \
433
+ (LIBBIN_OVR_INST_CONVERT | LIBBIN_OVR_SET_CONVERT | LIBBIN_OVR_CONVERT_FIELDS | LIBBIN_OVR_CONVERT_FIELD)
434
+
435
+ static uint64_t libbin_override_gen = 1;
436
+ static VALUE rb_data_types_file = Qnil;
437
+
438
+ static VALUE cStructure_method_added(VALUE self, VALUE mid) {
439
+ (void)self;
440
+ (void)mid;
441
+ LIBBIN_ATOMIC_INC(&libbin_override_gen);
442
+ return Qnil;
443
+ }
444
+
445
+ static VALUE cStructure_singleton_method_added(VALUE self, VALUE mid) {
446
+ (void)self;
447
+ (void)mid;
448
+ LIBBIN_ATOMIC_INC(&libbin_override_gen);
449
+ return Qnil;
450
+ }
451
+
452
+ static VALUE cStructure_bump_override_gen(VALUE self) {
453
+ (void)self;
454
+ LIBBIN_ATOMIC_INC(&libbin_override_gen);
455
+ return Qnil;
456
+ }
457
+
458
+ static VALUE cStructure_preprocess_expression(VALUE self, VALUE expr) {
459
+ (void)self;
460
+ return cField_preprocess_expression(expr);
461
+ }
462
+
463
+ static VALUE cStructure_set_data_types_file(VALUE self, VALUE path) {
464
+ (void)self;
465
+ Check_Type(path, T_STRING);
466
+ rb_data_types_file = rb_obj_freeze(rb_str_dup(path));
467
+ #ifdef HAVE_RB_RACTOR_MAKE_SHAREABLE
468
+ rb_ractor_make_shareable(rb_data_types_file);
469
+ #endif
470
+ rb_gc_register_mark_object(rb_data_types_file);
471
+ LIBBIN_ATOMIC_INC(&libbin_override_gen);
472
+ return Qnil;
473
+ }
239
474
 
240
- static VALUE cDataConverter_parent(VALUE self) {
241
- struct cDataConverter_data *data;
242
- TypedData_Get_Struct(self, struct cDataConverter_data, &cDataConverter_type, data);
243
- return data->__parent;
475
+ static inline int is_default_accessor_method(VALUE klass, ID mid) {
476
+ VALUE um = rb_funcall(klass, id_instance_method, 1, ID2SYM(mid));
477
+ if (!RTEST(rb_class_inherited_p(rb_funcall(um, id_owner, 0), cStructure)))
478
+ return 0;
479
+ VALUE sl = rb_funcall(um, id_source_location, 0);
480
+ if (!RB_TYPE_P(sl, T_ARRAY) || RARRAY_LEN(sl) < 1)
481
+ return 0;
482
+ if (NIL_P(rb_data_types_file))
483
+ return 0;
484
+ return RTEST(rb_str_equal(rb_ary_entry(sl, 0), rb_data_types_file));
485
+ }
486
+
487
+ static inline int method_owned_by(VALUE klass, ID mid, VALUE expected_owner) {
488
+ VALUE um = rb_funcall(klass, id_instance_method, 1, ID2SYM(mid));
489
+ return rb_funcall(um, id_owner, 0) == expected_owner;
490
+ }
491
+
492
+ static inline int singl_method_owned_by(VALUE klass, ID mid, VALUE expected_owner) {
493
+ VALUE m = rb_funcall(klass, id_method, 1, ID2SYM(mid));
494
+ return rb_funcall(m, id_owner, 0) == expected_owner;
495
+ }
496
+
497
+ static uint32_t libbin_compute_structure_flags(VALUE klass) {
498
+ uint32_t flags = 0;
499
+ if (!method_owned_by(klass, id_initialize, cStructure))
500
+ flags |= LIBBIN_OVR_INIT;
501
+ if (!method_owned_by(klass, id___load, cStructure))
502
+ flags |= LIBBIN_OVR_INST_LOAD;
503
+ if (!singl_method_owned_by(klass, id_load, cStructure_sclass))
504
+ flags |= LIBBIN_OVR_SINGL_LOAD;
505
+ if (!method_owned_by(klass, id___dump, cStructure))
506
+ flags |= LIBBIN_OVR_INST_DUMP;
507
+ if (!singl_method_owned_by(klass, id_dump, cStructure_sclass))
508
+ flags |= LIBBIN_OVR_SINGL_DUMP;
509
+ if (!method_owned_by(klass, id___convert, cStructure))
510
+ flags |= LIBBIN_OVR_INST_CONVERT;
511
+ if (!singl_method_owned_by(klass, id_convert, cStructure_sclass))
512
+ flags |= LIBBIN_OVR_SINGL_CONVERT;
513
+ if (!method_owned_by(klass, id___load_fields, cStructure))
514
+ flags |= LIBBIN_OVR_LOAD_FIELDS;
515
+ if (!method_owned_by(klass, id___dump_fields, cStructure))
516
+ flags |= LIBBIN_OVR_DUMP_FIELDS;
517
+ if (!method_owned_by(klass, id___convert_fields, cStructure))
518
+ flags |= LIBBIN_OVR_CONVERT_FIELDS;
519
+ if (!method_owned_by(klass, id___load_field, cStructure))
520
+ flags |= LIBBIN_OVR_LOAD_FIELD;
521
+ if (!method_owned_by(klass, id___dump_field, cStructure))
522
+ flags |= LIBBIN_OVR_DUMP_FIELD;
523
+ if (!method_owned_by(klass, id___convert_field, cStructure))
524
+ flags |= LIBBIN_OVR_CONVERT_FIELD;
525
+ if (!method_owned_by(klass, id___set_load_state, cStructure) ||
526
+ !method_owned_by(klass, id___unset_load_state, cStructure))
527
+ flags |= LIBBIN_OVR_SET_LOAD;
528
+ if (!method_owned_by(klass, id___set_dump_state, cStructure) ||
529
+ !method_owned_by(klass, id___unset_dump_state, cStructure))
530
+ flags |= LIBBIN_OVR_SET_DUMP;
531
+ if (!method_owned_by(klass, id___set_convert_state, cStructure) ||
532
+ !method_owned_by(klass, id___unset_convert_state, cStructure))
533
+ flags |= LIBBIN_OVR_SET_CONVERT;
534
+
535
+ VALUE stride = rb_attr_get(klass, id_stride);
536
+ int has_stride = RTEST(stride);
537
+ if (has_stride)
538
+ flags |= LIBBIN_HAS_STRIDE;
539
+
540
+ VALUE fields = rb_attr_get(klass, id_fields);
541
+ if (!RB_TYPE_P(fields, T_ARRAY)) {
542
+ flags |= LIBBIN_OVR_ACCESSORS;
543
+ } else {
544
+ int all_scalar_leaf = !has_stride;
545
+ for (long i = 0; i < RARRAY_LEN(fields); i++) {
546
+ VALUE field = rb_ary_entry(fields, i);
547
+ struct cField_data *fd;
548
+ TypedData_Get_Struct(field, struct cField_data, &cField_type, fd);
549
+ if (RTEST(fd->offset))
550
+ flags |= LIBBIN_HAS_OFFSET_FIELD;
551
+ if (!fd->is_static_simple || fd->scalar_kind == SCALAR_NONE)
552
+ all_scalar_leaf = 0;
553
+ if (!NIL_P(fd->name)) {
554
+ if (!is_default_accessor_method(klass, fd->getter) ||
555
+ !is_default_accessor_method(klass, fd->setter)) {
556
+ flags |= LIBBIN_OVR_ACCESSORS;
557
+ }
558
+ }
559
+ }
560
+ if (all_scalar_leaf && !(flags & LIBBIN_OVR_ACCESSORS))
561
+ flags |= LIBBIN_ALL_SCALAR_LEAF;
562
+ }
563
+ return flags;
244
564
  }
245
565
 
246
- static VALUE cDataConverter_index(VALUE self) {
247
- struct cDataConverter_data *data;
248
- TypedData_Get_Struct(self, struct cDataConverter_data, &cDataConverter_type, data);
249
- return data->__index;
566
+ struct libbin_set_flags_args {
567
+ VALUE klass;
568
+ uint32_t flags;
569
+ uint64_t gen;
570
+ };
571
+
572
+ static VALUE libbin_set_class_flags_cb(VALUE arg) {
573
+ struct libbin_set_flags_args *a = (struct libbin_set_flags_args *)arg;
574
+ rb_ivar_set(a->klass, id___libbin_flags, ULONG2NUM(a->flags));
575
+ rb_ivar_set(a->klass, id___libbin_flags_gen, ULL2NUM(a->gen));
576
+ return Qnil;
250
577
  }
251
578
 
252
- static VALUE cDataConverter_iterator(VALUE self) {
253
- struct cDataConverter_data *data;
254
- TypedData_Get_Struct(self, struct cDataConverter_data, &cDataConverter_type, data);
255
- return data->__iterator;
579
+ static inline uint32_t libbin_get_structure_flags(VALUE klass) {
580
+ uint64_t cur_gen = LIBBIN_ATOMIC_LOAD(&libbin_override_gen);
581
+ VALUE gen = rb_attr_get(klass, id___libbin_flags_gen);
582
+ if (!NIL_P(gen) && NUM2ULL(gen) == cur_gen) {
583
+ return (uint32_t)NUM2ULONG(rb_attr_get(klass, id___libbin_flags));
584
+ }
585
+ #ifdef HAVE_RB_RACTOR_LOCAL_STORAGE_VALUE_NEWKEY
586
+ VALUE rhash = rb_ractor_local_storage_value(libbin_ractor_flags_key);
587
+ if (RB_TYPE_P(rhash, T_HASH)) {
588
+ VALUE entry = rb_hash_lookup(rhash, klass);
589
+ if (RB_TYPE_P(entry, T_ARRAY) && RARRAY_LEN(entry) == 2 &&
590
+ NUM2ULL(rb_ary_entry(entry, 0)) == cur_gen) {
591
+ return (uint32_t)NUM2ULONG(rb_ary_entry(entry, 1));
592
+ }
593
+ }
594
+ #endif
595
+ uint32_t flags = libbin_compute_structure_flags(klass);
596
+ struct libbin_set_flags_args args = { klass, flags, cur_gen };
597
+ int state = 0;
598
+ rb_protect(libbin_set_class_flags_cb, (VALUE)&args, &state);
599
+ if (state) {
600
+ VALUE err = rb_errinfo();
601
+ if (rb_obj_is_kind_of(err, rb_eStandardError)) {
602
+ rb_set_errinfo(Qnil);
603
+ #ifdef HAVE_RB_RACTOR_LOCAL_STORAGE_VALUE_NEWKEY
604
+ if (!RB_TYPE_P(rhash, T_HASH)) {
605
+ rhash = rb_hash_new();
606
+ rb_ractor_local_storage_value_set(libbin_ractor_flags_key, rhash);
607
+ }
608
+ rb_hash_aset(rhash, klass, rb_ary_new_from_args(2, ULL2NUM(cur_gen), ULONG2NUM(flags)));
609
+ #endif
610
+ } else {
611
+ rb_jump_tag(state);
612
+ }
613
+ }
614
+ return flags;
615
+ }
616
+
617
+ void libbin_ctx_sync_to_ruby(libbin_ctx_t *ctx) {
618
+ if (!ctx)
619
+ return;
620
+ if (ctx->has_in)
621
+ libbin_io_sync_to_ruby(&ctx->in_io);
622
+ if (ctx->has_out)
623
+ libbin_io_sync_to_ruby(&ctx->out_io);
624
+ }
625
+
626
+ void libbin_ctx_sync_from_ruby(libbin_ctx_t *ctx) {
627
+ if (!ctx)
628
+ return;
629
+ if (ctx->has_in)
630
+ libbin_io_sync_from_ruby(&ctx->in_io);
631
+ if (ctx->has_out)
632
+ libbin_io_sync_from_ruby(&ctx->out_io);
633
+ }
634
+
635
+ libbin_ctx_t *libbin_ctx_from_parent(VALUE parent, VALUE input, VALUE output, uint8_t mode) {
636
+ if (!RTEST(parent) || !rb_obj_is_kind_of(parent, cStructure))
637
+ return NULL;
638
+ struct cStructure_data *pdata;
639
+ TypedData_Get_Struct(parent, struct cStructure_data, &cStructure_type, pdata);
640
+ libbin_ctx_t *ctx = pdata->active_ctx;
641
+ if (!ctx)
642
+ return NULL;
643
+ if (mode == 0 && (!ctx->has_in || ctx->in_io.io != input))
644
+ return NULL;
645
+ if (mode == 1 && (!ctx->has_out || ctx->out_io.io != output))
646
+ return NULL;
647
+ if (mode == 2 && (!ctx->has_in || !ctx->has_out || ctx->in_io.io != input || ctx->out_io.io != output))
648
+ return NULL;
649
+ return ctx;
650
+ }
651
+
652
+ static inline VALUE cStructure_restore_context(VALUE self) {
653
+ struct cStructure_data *data;
654
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
655
+ data->__iterator = Qnil;
656
+ data->__type = Qnil;
657
+ data->__length = Qnil;
658
+ data->__count = Qnil;
659
+ data->__offset = Qnil;
660
+ data->__condition = Qnil;
661
+ data->__value = Qnil;
662
+ return Qnil;
256
663
  }
257
664
 
258
- static VALUE cDataConverter_position(VALUE self) {
259
- struct cDataConverter_data *data;
260
- TypedData_Get_Struct(self, struct cDataConverter_data, &cDataConverter_type, data);
261
- return data->__position;
665
+ static inline void libbin_unset_frame_state(VALUE self, uint8_t mode) {
666
+ struct cStructure_data *data;
667
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
668
+ if (mode == 0 || mode == 2) {
669
+ data->__input = Qnil;
670
+ data->__input_big = Qnil;
671
+ }
672
+ if (mode == 1 || mode == 2) {
673
+ data->__output = Qnil;
674
+ data->__output_big = Qnil;
675
+ }
676
+ data->__parent = Qnil;
677
+ data->__index = Qnil;
678
+ data->__position = Qnil;
679
+ data->__cur_position = Qnil;
680
+ data->active_ctx = NULL;
681
+ cStructure_restore_context(self);
682
+ }
683
+
684
+ static void libbin_print_frame_error(VALUE self, VALUE field) {
685
+ VALUE out = rb_funcall(mLibBin, id_output, 0);
686
+ if (NIL_P(out))
687
+ return;
688
+ if (NIL_P(field)) {
689
+ struct cStructure_data *data;
690
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
691
+ rb_funcall(out, id_print, 6,
692
+ rb_obj_class(self),
693
+ rb_str_new_cstr(": could not load fields, index: "),
694
+ data->__index,
695
+ rb_str_new_cstr(", current position: "),
696
+ data->__cur_position,
697
+ rb_str_new_cstr("\n"));
698
+ } else {
699
+ struct cField_data *field_data;
700
+ TypedData_Get_Struct(field, struct cField_data, &cField_type, field_data);
701
+ rb_funcall(out, id_print, 6,
702
+ rb_obj_class(self),
703
+ rb_str_new_cstr(": "),
704
+ field_data->name,
705
+ rb_str_new_cstr("("),
706
+ field_data->type,
707
+ rb_str_new_cstr(")\n"));
708
+ }
262
709
  }
263
710
 
264
- /* attr_reader :__input
265
- attr_reader :__output
266
- attr_reader :__input_big
267
- attr_reader :__output_big */
711
+ static void libbin_attach_error_context(
712
+ VALUE exception,
713
+ VALUE self,
714
+ VALUE field,
715
+ libbin_ctx_t *ctx,
716
+ uint8_t mode,
717
+ VALUE frame_index)
718
+ {
719
+ if (!rb_obj_is_kind_of(exception, eLibBinError))
720
+ return;
721
+ if (!NIL_P(rb_attr_get(exception, id_ivar_structure)))
722
+ return;
723
+
724
+ rb_ivar_set(exception, id_ivar_structure, rb_obj_class(self));
725
+
726
+ struct cField_data *fd = NULL;
727
+ if (!NIL_P(field)) {
728
+ TypedData_Get_Struct(field, struct cField_data, &cField_type, fd);
729
+ rb_ivar_set(exception, id_ivar_field, fd->name);
730
+ } else {
731
+ rb_ivar_set(exception, id_ivar_field, Qnil);
732
+ }
733
+
734
+ if (NIL_P(rb_attr_get(exception, id_ivar_offset))) {
735
+ VALUE off = Qnil;
736
+ if (ctx) {
737
+ libbin_io_t *bio = (mode == 1 && ctx->has_out)
738
+ ? &ctx->out_io
739
+ : (ctx->has_in ? &ctx->in_io : NULL);
740
+ if (bio) {
741
+ if (bio->kind != LIBBIN_IO_GENERIC || bio->non_seekable) {
742
+ off = LL2NUM(bio->pos);
743
+ } else {
744
+ ptrdiff_t pos = 0;
745
+ if (libbin_try_tell_io(bio->io, &pos))
746
+ off = LL2NUM(pos);
747
+ }
748
+ }
749
+ }
750
+ if (NIL_P(off)) {
751
+ struct cStructure_data *data;
752
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
753
+ off = !NIL_P(data->__cur_position) ? data->__cur_position : data->__position;
754
+ }
755
+ rb_ivar_set(exception, id_ivar_offset, off);
756
+ }
757
+
758
+ if (NIL_P(rb_attr_get(exception, id_ivar_index))) {
759
+ struct cStructure_data *data;
760
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
761
+ VALUE idx = Qnil;
762
+ if (fd && RTEST(fd->count) && !NIL_P(data->__iterator)) {
763
+ idx = data->__iterator;
764
+ } else if (!NIL_P(data->__index)) {
765
+ idx = data->__index;
766
+ } else if (!NIL_P(frame_index)) {
767
+ idx = frame_index;
768
+ }
769
+ rb_ivar_set(exception, id_ivar_index, idx);
770
+ }
771
+ }
268
772
 
269
- static VALUE cDataConverter_input(VALUE self) {
270
- struct cDataConverter_data *data;
271
- TypedData_Get_Struct(self, struct cDataConverter_data, &cDataConverter_type, data);
272
- return data->__input;
773
+ static VALUE libbin_ctx_rescue(VALUE ctx_p, VALUE exception) {
774
+ libbin_ctx_t *ctx = (libbin_ctx_t *)ctx_p;
775
+ while (ctx->frame_depth > 0) {
776
+ libbin_frame_t f = ctx->frames[--ctx->frame_depth];
777
+ libbin_attach_error_context(exception, f.self, f.field, ctx, f.mode, f.index);
778
+ libbin_print_frame_error(f.self, f.field);
779
+ libbin_unset_frame_state(f.self, f.mode);
780
+ }
781
+ libbin_ctx_sync_to_ruby(ctx);
782
+ rb_exc_raise(exception);
783
+ return Qnil;
273
784
  }
274
785
 
275
- static VALUE cDataConverter_output(VALUE self) {
276
- struct cDataConverter_data *data;
277
- TypedData_Get_Struct(self, struct cDataConverter_data, &cDataConverter_type, data);
278
- return data->__output;
786
+ static VALUE libbin_ctx_ensure(VALUE ctx_p) {
787
+ libbin_ctx_t *ctx = (libbin_ctx_t *)ctx_p;
788
+ while (ctx->frame_depth > 0) {
789
+ libbin_frame_t f = ctx->frames[--ctx->frame_depth];
790
+ libbin_unset_frame_state(f.self, f.mode);
791
+ }
792
+ libbin_ctx_sync_to_ruby(ctx);
793
+ return Qnil;
279
794
  }
280
795
 
281
- static VALUE cDataConverter_input_big(VALUE self) {
282
- struct cDataConverter_data *data;
283
- TypedData_Get_Struct(self, struct cDataConverter_data, &cDataConverter_type, data);
284
- return data->__input_big;
796
+ static inline void libbin_ctx_init_load(libbin_ctx_t *ctx, VALUE input) {
797
+ libbin_io_init(&ctx->in_io, input, 0);
798
+ ctx->pending_index = Qnil;
799
+ ctx->has_in = 1;
800
+ ctx->has_out = 0;
801
+ ctx->frame_depth = 0;
285
802
  }
286
803
 
287
- static VALUE cDataConverter_output_big(VALUE self) {
288
- struct cDataConverter_data *data;
289
- TypedData_Get_Struct(self, struct cDataConverter_data, &cDataConverter_type, data);
290
- return data->__output_big;
804
+ static inline void libbin_ctx_init_dump(libbin_ctx_t *ctx, VALUE output) {
805
+ libbin_io_init(&ctx->out_io, output, 1);
806
+ ctx->pending_index = Qnil;
807
+ ctx->has_in = 0;
808
+ ctx->has_out = 1;
809
+ ctx->frame_depth = 0;
291
810
  }
292
811
 
293
- ID id_tell;
812
+ static inline void libbin_ctx_init_convert(libbin_ctx_t *ctx, VALUE input, VALUE output) {
813
+ if (input == output) {
814
+ libbin_io_init_generic(&ctx->in_io, input, 0);
815
+ libbin_io_init_generic(&ctx->out_io, output, 1);
816
+ } else {
817
+ libbin_io_init(&ctx->in_io, input, 0);
818
+ libbin_io_init(&ctx->out_io, output, 1);
819
+ }
820
+ ctx->pending_index = Qnil;
821
+ ctx->has_in = 1;
822
+ ctx->has_out = 1;
823
+ ctx->frame_depth = 0;
824
+ }
825
+
826
+ static inline size_t libbin_ctx_push_frame(libbin_ctx_t *ctx, VALUE self, uint8_t mode, VALUE frame_index) {
827
+ size_t depth = ctx->frame_depth;
828
+ if (depth < LIBBIN_MAX_FRAMES) {
829
+ ctx->frames[depth].self = self;
830
+ ctx->frames[depth].field = Qnil;
831
+ ctx->frames[depth].index = frame_index;
832
+ ctx->frames[depth].mode = mode;
833
+ ctx->frame_depth = depth + 1;
834
+ }
835
+ return depth;
836
+ }
294
837
 
295
- /* def __set_convert_type(input, output, input_big, output_big, parent, index)
296
- @__input_big = input_big
297
- @__output_big = output_big
298
- @__input = input
299
- @__output = output
300
- @__parent = parent
301
- @__index = index
302
- @__position = input.tell
303
- @__cur_position = @__position
304
- end */
838
+ static inline void libbin_ctx_pop_frame(libbin_ctx_t *ctx, size_t depth) {
839
+ if (depth < LIBBIN_MAX_FRAMES)
840
+ ctx->frame_depth = depth;
841
+ }
305
842
 
306
- static inline VALUE cDataConverter_set_convert_type(
843
+ static VALUE cStructure_set_convert_state(
307
844
  VALUE self,
308
845
  VALUE input,
309
846
  VALUE output,
@@ -312,59 +849,63 @@ static inline VALUE cDataConverter_set_convert_type(
312
849
  VALUE parent,
313
850
  VALUE index)
314
851
  {
315
- struct cDataConverter_data *data;
316
- TypedData_Get_Struct(self, struct cDataConverter_data, &cDataConverter_type, data);
852
+ struct cStructure_data *data;
853
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
317
854
  data->__input = input;
318
855
  data->__output = output;
319
856
  data->__input_big = input_big;
320
857
  data->__output_big = output_big;
321
858
  data->__parent = parent;
322
859
  data->__index = index;
323
- data->__position = rb_funcall(input, id_tell, 0);
860
+ libbin_ctx_t *pctx = libbin_ctx_from_parent(parent, input, output, 2);
861
+ if (pctx) {
862
+ libbin_ctx_sync_from_ruby(pctx);
863
+ data->active_ctx = pctx;
864
+ data->__position = LL2NUM(libbin_io_tell(&pctx->in_io));
865
+ } else {
866
+ ptrdiff_t pos = 0;
867
+ data->active_ctx = NULL;
868
+ data->__position = libbin_try_tell_io(input, &pos) ? LL2NUM(pos) : INT2FIX(0);
869
+ }
324
870
  data->__cur_position = data->__position;
325
871
  return Qnil;
326
872
  }
327
873
 
328
- /* def __unset_convert_type
329
- @__input_big = nil
330
- @__output_big = nil
331
- @__input = nil
332
- @__output = nil
333
- @__parent = nil
334
- @__index = nil
335
- @__position = nil
336
- @__cur_position = nil
337
- end */
338
-
339
- static inline VALUE cDataConverter_unset_convert_type(VALUE self) {
340
- struct cDataConverter_data *data;
341
- TypedData_Get_Struct(self, struct cDataConverter_data, &cDataConverter_type, data);
342
- data->__input = Qnil;
343
- data->__output = Qnil;
344
- data->__input_big = Qnil;
345
- data->__output_big = Qnil;
874
+ static inline VALUE cStructure_unset_state_mode(VALUE self, uint8_t mode) {
875
+ struct cStructure_data *data;
876
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
877
+ if (data->active_ctx) {
878
+ libbin_ctx_sync_to_ruby(data->active_ctx);
879
+ data->active_ctx = NULL;
880
+ }
881
+ if (mode == 0 || mode == 2) {
882
+ data->__input = Qnil;
883
+ data->__input_big = Qnil;
884
+ }
885
+ if (mode == 1 || mode == 2) {
886
+ data->__output = Qnil;
887
+ data->__output_big = Qnil;
888
+ }
346
889
  data->__parent = Qnil;
347
890
  data->__index = Qnil;
348
891
  data->__position = Qnil;
349
892
  data->__cur_position = Qnil;
893
+ cStructure_restore_context(self);
350
894
  return Qnil;
351
895
  }
352
896
 
353
- /* def __set_size_type(position, parent, index)
354
- @__parent = parent
355
- @__index = index
356
- @__position = position
357
- @__cur_position = @__position
358
- end */
897
+ static VALUE cStructure_unset_convert_state(VALUE self) {
898
+ return cStructure_unset_state_mode(self, 2);
899
+ }
359
900
 
360
- static inline VALUE cDataConverter_set_size_type(
901
+ static VALUE cStructure_set_size_state(
361
902
  VALUE self,
362
903
  VALUE position,
363
904
  VALUE parent,
364
905
  VALUE index)
365
906
  {
366
- struct cDataConverter_data *data;
367
- TypedData_Get_Struct(self, struct cDataConverter_data, &cDataConverter_type, data);
907
+ struct cStructure_data *data;
908
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
368
909
  data->__parent = parent;
369
910
  data->__index = index;
370
911
  data->__position = position;
@@ -372,229 +913,249 @@ static inline VALUE cDataConverter_set_size_type(
372
913
  return Qnil;
373
914
  }
374
915
 
375
- /* def __unset_size_type
376
- @__parent = nil
377
- @__index = nil
378
- @__position = nil
379
- @__cur_position = nil
380
- end */
381
-
382
- static inline VALUE cDataConverter_unset_size_type(VALUE self) {
383
- struct cDataConverter_data *data;
384
- TypedData_Get_Struct(self, struct cDataConverter_data, &cDataConverter_type, data);
916
+ static VALUE cStructure_unset_size_state(VALUE self) {
917
+ struct cStructure_data *data;
918
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
385
919
  data->__parent = Qnil;
386
920
  data->__index = Qnil;
387
921
  data->__position = Qnil;
388
922
  data->__cur_position = Qnil;
923
+ cStructure_restore_context(self);
389
924
  return Qnil;
390
925
  }
391
926
 
392
- /* def __set_load_type(input, input_big, parent, index)
393
- @__input_big = input_big
394
- @__input = input
395
- @__parent = parent
396
- @__index = index
397
- @__position = input.tell
398
- @__cur_position = @__position
399
- end */
400
-
401
- static inline VALUE cDataConverter_set_load_type(
927
+ static VALUE cStructure_set_load_state(
402
928
  VALUE self,
403
929
  VALUE input,
404
930
  VALUE input_big,
405
931
  VALUE parent,
406
932
  VALUE index)
407
933
  {
408
- struct cDataConverter_data *data;
409
- TypedData_Get_Struct(self, struct cDataConverter_data, &cDataConverter_type, data);
934
+ struct cStructure_data *data;
935
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
410
936
  data->__input = input;
411
937
  data->__input_big = input_big;
412
938
  data->__parent = parent;
413
939
  data->__index = index;
414
- data->__position = rb_funcall(input, id_tell, 0);
940
+ libbin_ctx_t *pctx = libbin_ctx_from_parent(parent, input, Qnil, 0);
941
+ if (pctx) {
942
+ libbin_ctx_sync_from_ruby(pctx);
943
+ data->active_ctx = pctx;
944
+ data->__position = LL2NUM(libbin_io_tell(&pctx->in_io));
945
+ } else {
946
+ ptrdiff_t pos = 0;
947
+ data->active_ctx = NULL;
948
+ data->__position = libbin_try_tell_io(input, &pos) ? LL2NUM(pos) : INT2FIX(0);
949
+ }
415
950
  data->__cur_position = data->__position;
416
951
  return Qnil;
417
952
  }
418
953
 
419
- /* def __unset_load_type
420
- @__input_big = nil
421
- @__input = nil
422
- @__parent = nil
423
- @__index = nil
424
- @__position = nil
425
- @__cur_position = nil
426
- end */
427
-
428
- static inline VALUE cDataConverter_unset_load_type(VALUE self) {
429
- struct cDataConverter_data *data;
430
- TypedData_Get_Struct(self, struct cDataConverter_data, &cDataConverter_type, data);
431
- data->__input = Qnil;
432
- data->__input_big = Qnil;
433
- data->__parent = Qnil;
434
- data->__index = Qnil;
435
- data->__position = Qnil;
436
- data->__cur_position = Qnil;
437
- return Qnil;
954
+ static VALUE cStructure_unset_load_state(VALUE self) {
955
+ return cStructure_unset_state_mode(self, 0);
438
956
  }
439
957
 
440
- /* def __set_dump_type(output, output_big, parent, index)
441
- @__output_big = output_big
442
- @__output = output
443
- @__parent = parent
444
- @__index = index
445
- @__position = output.tell
446
- @__cur_position = @__position
447
- end */
448
-
449
- static inline VALUE cDataConverter_set_dump_type(
958
+ static VALUE cStructure_set_dump_state(
450
959
  VALUE self,
451
960
  VALUE output,
452
961
  VALUE output_big,
453
962
  VALUE parent,
454
963
  VALUE index)
455
964
  {
456
- struct cDataConverter_data *data;
457
- TypedData_Get_Struct(self, struct cDataConverter_data, &cDataConverter_type, data);
965
+ struct cStructure_data *data;
966
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
458
967
  data->__output = output;
459
968
  data->__output_big = output_big;
460
969
  data->__parent = parent;
461
970
  data->__index = index;
462
- data->__position = rb_funcall(output, id_tell, 0);
971
+ libbin_ctx_t *pctx = libbin_ctx_from_parent(parent, Qnil, output, 1);
972
+ if (pctx) {
973
+ libbin_ctx_sync_from_ruby(pctx);
974
+ data->active_ctx = pctx;
975
+ data->__position = LL2NUM(libbin_io_tell(&pctx->out_io));
976
+ } else {
977
+ ptrdiff_t pos = 0;
978
+ data->active_ctx = NULL;
979
+ data->__position = libbin_try_tell_io(output, &pos) ? LL2NUM(pos) : INT2FIX(0);
980
+ }
463
981
  data->__cur_position = data->__position;
464
982
  return Qnil;
465
983
  }
466
984
 
467
- /* def __unset_dump_type
468
- @__output_big = nil
469
- @__output = nil
470
- @__parent = nil
471
- @__index = nil
472
- @__position = nil
473
- @__cur_position = nil
474
- end */
475
-
476
- static inline VALUE cDataConverter_unset_dump_type(VALUE self) {
477
- struct cDataConverter_data *data;
478
- TypedData_Get_Struct(self, struct cDataConverter_data, &cDataConverter_type, data);
479
- data->__output = Qnil;
480
- data->__output_big = Qnil;
481
- data->__parent = Qnil;
482
- data->__index = Qnil;
483
- data->__position = Qnil;
484
- data->__cur_position = Qnil;
485
- return Qnil;
985
+ static VALUE cStructure_unset_dump_state(VALUE self) {
986
+ return cStructure_unset_state_mode(self, 1);
486
987
  }
487
988
 
488
- /* def __decode_expression(sym)
489
- case sym
490
- when Proc
491
- return sym.call
492
- else
493
- return sym
494
- end
495
- end */
496
-
497
- static ID id_instance_exec;
498
-
499
- static inline VALUE cDataConverter_decode_expression(VALUE self, VALUE expression) {
500
- if (rb_obj_is_proc(expression))
501
- return rb_funcall_with_block(self, id_instance_exec, 0, NULL, expression);
502
- else
503
- return expression;
989
+ static inline VALUE cStructure_decode_expression_ctx(VALUE self, libbin_ctx_t *ctx, VALUE expression) {
990
+ if (rb_obj_is_proc(expression)) {
991
+ libbin_ctx_sync_to_ruby(ctx);
992
+ VALUE res = rb_funcall_with_block(self, id_instance_exec, 0, NULL, expression);
993
+ libbin_ctx_sync_from_ruby(ctx);
994
+ return res;
995
+ }
996
+ return expression;
997
+ }
998
+
999
+ static VALUE cStructure_decode_expression(VALUE self, VALUE expression) {
1000
+ struct cStructure_data *data;
1001
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
1002
+ return cStructure_decode_expression_ctx(self, data->active_ctx, expression);
1003
+ }
1004
+
1005
+ static inline void cStructure_raise_validation_error(VALUE msg, ptrdiff_t field_start) {
1006
+ VALUE exc = rb_exc_new_str(eLibBinValidationError, msg);
1007
+ if (field_start >= 0)
1008
+ rb_ivar_set(exc, id_ivar_offset, LL2NUM(field_start));
1009
+ rb_exc_raise(exc);
1010
+ }
1011
+
1012
+ static inline VALUE cStructure_decode_expect_ctx(VALUE self, libbin_ctx_t *ctx, VALUE expect, VALUE val, ptrdiff_t field_start) {
1013
+ if (NIL_P(expect))
1014
+ return val;
1015
+ if (rb_obj_is_proc(expect)) {
1016
+ libbin_ctx_sync_to_ruby(ctx);
1017
+ VALUE ok = rb_funcall_with_block(self, id_instance_exec, 1, &val, expect);
1018
+ libbin_ctx_sync_from_ruby(ctx);
1019
+ if (!RTEST(ok))
1020
+ cStructure_raise_validation_error(rb_sprintf("could not validate field value: %"PRIsVALUE, val), field_start);
1021
+ } else if (!RTEST(rb_equal(expect, val))) {
1022
+ cStructure_raise_validation_error(
1023
+ rb_sprintf("could not validate field value: %"PRIsVALUE" expected: %"PRIsVALUE, val, expect),
1024
+ field_start);
1025
+ }
1026
+ return val;
504
1027
  }
505
1028
 
506
- /* def __decode_seek_offset(offset, relative_offset)
507
- return nil unless offset
508
- offset = __decode_expression(offset)
509
- return false if offset == 0x0
510
- offset += @__position if relative_offset
511
- @__cur_position = offset
512
- @__input.seek(offset) if @__input
513
- @__output.seek(offset) if @__output
514
- offset
515
- end */
516
-
517
- ID id_seek;
1029
+ static VALUE cStructure_decode_expect(VALUE self, VALUE expect, VALUE val) {
1030
+ struct cStructure_data *data;
1031
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
1032
+ return cStructure_decode_expect_ctx(self, data->active_ctx, expect, val, -1);
1033
+ }
518
1034
 
519
- static inline VALUE cDataConverter_decode_seek_offset(VALUE self, VALUE offset, VALUE relative_offset) {
520
- struct cDataConverter_data *data;
521
- TypedData_Get_Struct(self, struct cDataConverter_data, &cDataConverter_type, data);
522
- if (!RTEST(offset))
523
- return Qnil;
524
- ptrdiff_t off = NUM2LL(cDataConverter_decode_expression(self, offset));
525
- if (off == 0)
526
- return Qfalse;
527
- if (RTEST(relative_offset))
528
- off += NUM2LL(data->__position);
529
- data->__cur_position = LL2NUM(off);
530
- if (RTEST(data->__input))
531
- rb_funcall(data->__input, id_seek, 1, data->__cur_position);
532
- if (RTEST(data->__output))
533
- rb_funcall(data->__output, id_seek, 1, data->__cur_position);
1035
+ static inline VALUE cStructure_decode_seek_offset_ctx(
1036
+ VALUE self,
1037
+ libbin_ctx_t *ctx,
1038
+ VALUE offset,
1039
+ VALUE relative_offset,
1040
+ VALUE align,
1041
+ VALUE null_offset)
1042
+ {
1043
+ struct cStructure_data *data;
1044
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
1045
+ ptrdiff_t cur_pos;
1046
+ if (!RTEST(offset)) {
1047
+ if (!RTEST(align))
1048
+ return Qnil;
1049
+ if (ctx && ctx->has_in)
1050
+ cur_pos = libbin_io_tell(&ctx->in_io);
1051
+ else if (ctx && ctx->has_out)
1052
+ cur_pos = libbin_io_tell(&ctx->out_io);
1053
+ else if (RTEST(data->__input)) {
1054
+ ptrdiff_t pos = 0;
1055
+ cur_pos = libbin_try_tell_io(data->__input, &pos) ? pos : NUM2LL(data->__cur_position);
1056
+ } else if (RTEST(data->__output)) {
1057
+ ptrdiff_t pos = 0;
1058
+ cur_pos = libbin_try_tell_io(data->__output, &pos) ? pos : NUM2LL(data->__cur_position);
1059
+ } else
1060
+ cur_pos = NUM2LL(data->__cur_position);
1061
+ ptrdiff_t al = NUM2LL(align);
1062
+ ptrdiff_t pad;
1063
+ if ((pad = ((-cur_pos) & (al - 1))) == 0)
1064
+ return Qnil;
1065
+ cur_pos += pad;
1066
+ } else {
1067
+ VALUE off_val = cStructure_decode_expression_ctx(self, ctx, offset);
1068
+ if (NIL_P(off_val) || off_val == Qfalse)
1069
+ return Qfalse;
1070
+ cur_pos = NUM2LL(off_val);
1071
+ if (RTEST(null_offset) && cur_pos == NUM2LL(null_offset))
1072
+ return Qfalse;
1073
+ if (RTEST(relative_offset))
1074
+ cur_pos += NUM2LL(data->__position);
1075
+ if (RTEST(align)) {
1076
+ ptrdiff_t al = NUM2LL(align);
1077
+ cur_pos += (-cur_pos) & (al - 1);
1078
+ }
1079
+ }
1080
+ data->__cur_position = LL2NUM(cur_pos);
1081
+ if (ctx) {
1082
+ if (ctx->has_in)
1083
+ libbin_io_seek(&ctx->in_io, cur_pos);
1084
+ if (ctx->has_out)
1085
+ libbin_io_seek(&ctx->out_io, cur_pos);
1086
+ } else {
1087
+ if (RTEST(data->__input))
1088
+ rb_funcall(data->__input, id_seek, 1, data->__cur_position);
1089
+ if (RTEST(data->__output))
1090
+ rb_funcall(data->__output, id_seek, 1, data->__cur_position);
1091
+ }
534
1092
  return data->__cur_position;
535
1093
  }
536
1094
 
537
- /* def __decode_condition(condition)
538
- return true unless condition
539
- __decode_expression(condition)
540
- end */
1095
+ static VALUE cStructure_decode_seek_offset(
1096
+ VALUE self,
1097
+ VALUE offset,
1098
+ VALUE relative_offset,
1099
+ VALUE align,
1100
+ VALUE null_offset) {
1101
+ struct cStructure_data *data;
1102
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
1103
+ libbin_ctx_sync_from_ruby(data->active_ctx);
1104
+ VALUE res = cStructure_decode_seek_offset_ctx(self, data->active_ctx, offset, relative_offset, align, null_offset);
1105
+ libbin_ctx_sync_to_ruby(data->active_ctx);
1106
+ return res;
1107
+ }
541
1108
 
542
- static inline VALUE cDataConverter_decode_condition(VALUE self, VALUE condition) {
1109
+ static inline VALUE cStructure_decode_condition_ctx(VALUE self, libbin_ctx_t *ctx, VALUE condition) {
543
1110
  if (!RTEST(condition))
544
1111
  return Qtrue;
545
- return cDataConverter_decode_expression(self, condition);
1112
+ return cStructure_decode_expression_ctx(self, ctx, condition);
546
1113
  }
547
1114
 
548
- /* def __decode_count(count)
549
- return 1 unless count
550
- __decode_expression(count)
551
- end */
1115
+ static VALUE cStructure_decode_condition(VALUE self, VALUE condition) {
1116
+ struct cStructure_data *data;
1117
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
1118
+ return cStructure_decode_condition_ctx(self, data->active_ctx, condition);
1119
+ }
552
1120
 
553
- static inline VALUE cDataConverter_decode_count(VALUE self, VALUE count) {
1121
+ static inline VALUE cStructure_decode_count_ctx(VALUE self, libbin_ctx_t *ctx, VALUE count) {
554
1122
  if (!RTEST(count))
555
1123
  return INT2FIX(1);
556
- return cDataConverter_decode_expression(self, count);
1124
+ return cStructure_decode_expression_ctx(self, ctx, count);
557
1125
  }
558
1126
 
559
- /* def __decode_type(type)
560
- __decode_expression(type)
561
- end */
1127
+ static VALUE cStructure_decode_count(VALUE self, VALUE count) {
1128
+ struct cStructure_data *data;
1129
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
1130
+ return cStructure_decode_count_ctx(self, data->active_ctx, count);
1131
+ }
562
1132
 
563
- static inline VALUE cDataConverter_decode_type(VALUE self, VALUE type) {
564
- return cDataConverter_decode_expression(self, type);
1133
+ static inline VALUE cStructure_decode_type_ctx(VALUE self, libbin_ctx_t *ctx, VALUE type) {
1134
+ return cStructure_decode_expression_ctx(self, ctx, type);
565
1135
  }
566
1136
 
567
- /* def __decode_length(length)
568
- __decode_expression(length)
569
- end */
1137
+ static VALUE cStructure_decode_type(VALUE self, VALUE type) {
1138
+ struct cStructure_data *data;
1139
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
1140
+ return cStructure_decode_type_ctx(self, data->active_ctx, type);
1141
+ }
570
1142
 
571
- static inline VALUE cDataConverter_decode_length(VALUE self, VALUE length) {
1143
+ static inline VALUE cStructure_decode_length_ctx(VALUE self, libbin_ctx_t *ctx, VALUE length) {
572
1144
  if (NIL_P(length))
573
1145
  return Qnil;
574
- return cDataConverter_decode_expression(self, length);
575
- }
576
-
577
- /* def __decode_static_conditions(field)
578
- @__offset = nil
579
- @__condition = nil
580
- @__type = nil
581
- @__length = nil
582
- @__count = nil
583
- unless field.sequence?
584
- @__offset = __decode_seek_offset(field.offset, field.relative_offset?)
585
- throw :ignored, nil if @__offset == false
586
- @__condition = __decode_condition(field.condition)
587
- throw :ignored, nil unless @__condition
588
- @__type = __decode_type(field.type)
589
- @__length = __decode_length(field.length)
590
- end
591
- @__count = __decode_count(field.count)
592
- end */
593
-
594
- static inline VALUE cDataConverter_decode_static_conditions(VALUE self, VALUE field) {
595
- struct cDataConverter_data *data;
1146
+ return cStructure_decode_expression_ctx(self, ctx, length);
1147
+ }
1148
+
1149
+ static VALUE cStructure_decode_length(VALUE self, VALUE length) {
1150
+ struct cStructure_data *data;
1151
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
1152
+ return cStructure_decode_length_ctx(self, data->active_ctx, length);
1153
+ }
1154
+
1155
+ static inline VALUE cStructure_decode_static_conditions_ctx(VALUE self, libbin_ctx_t *ctx, VALUE field) {
1156
+ struct cStructure_data *data;
596
1157
  struct cField_data *field_data;
597
- TypedData_Get_Struct(self, struct cDataConverter_data, &cDataConverter_type, data);
1158
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
598
1159
  TypedData_Get_Struct(field, struct cField_data, &cField_type, field_data);
599
1160
  data->__offset = Qnil;
600
1161
  data->__condition = Qnil;
@@ -602,308 +1163,381 @@ static inline VALUE cDataConverter_decode_static_conditions(VALUE self, VALUE fi
602
1163
  data->__length = Qnil;
603
1164
  data->__count = Qnil;
604
1165
  if (!RTEST(field_data->sequence)) {
605
- data->__offset = cDataConverter_decode_seek_offset(self, field_data->offset, field_data->relative_offset);
606
- if (!data->__offset)
607
- return Qnil;
608
- data->__condition = cDataConverter_decode_condition(self, field_data->condition);
1166
+ data->__condition = cStructure_decode_condition_ctx(self, ctx, field_data->condition);
609
1167
  if (!RTEST(data->__condition))
610
1168
  return Qnil;
611
- data->__type = cDataConverter_decode_type(self, field_data->type);
612
- data->__length = cDataConverter_decode_length(self, field_data->length);
1169
+ data->__offset = cStructure_decode_seek_offset_ctx(self, ctx, field_data->offset, field_data->relative_offset, field_data->align, field_data->null_offset);
1170
+ if (data->__offset == Qfalse)
1171
+ return Qnil;
1172
+ data->__type = cStructure_decode_type_ctx(self, ctx, field_data->type);
1173
+ data->__length = cStructure_decode_length_ctx(self, ctx, field_data->length);
613
1174
  }
614
- data->__count = cDataConverter_decode_count(self, field_data->count);
1175
+ data->__count = cStructure_decode_count_ctx(self, ctx, field_data->count);
615
1176
  return Qtrue;
616
1177
  }
617
1178
 
618
- /* def __decode_dynamic_conditions(field)
619
- return true unless field.sequence?
620
- @__offset = nil
621
- @__condition = nil
622
- @__type = nil
623
- @__length = nil
624
- @__offset = __decode_seek_offset(field.offset, field.relative_offset?)
625
- return false if @__offset == false
626
- @__condition = __decode_condition(field.condition)
627
- return false unless @__condition
628
- @__type = __decode_type(field.type)
629
- @__length = __decode_length(field.length)
630
- return true
631
- end */
632
-
633
- static inline VALUE cDataConverter_decode_dynamic_conditions(VALUE self, VALUE field) {
634
- struct cDataConverter_data *data;
1179
+ static VALUE cStructure_decode_static_conditions(VALUE self, VALUE field) {
1180
+ struct cStructure_data *data;
1181
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
1182
+ return cStructure_decode_static_conditions_ctx(self, data->active_ctx, field);
1183
+ }
1184
+
1185
+ static inline VALUE cStructure_decode_dynamic_conditions_ctx(VALUE self, libbin_ctx_t *ctx, VALUE field) {
1186
+ struct cStructure_data *data;
635
1187
  struct cField_data *field_data;
636
1188
  TypedData_Get_Struct(field, struct cField_data, &cField_type, field_data);
637
1189
  if (!RTEST(field_data->sequence))
638
1190
  return Qtrue;
639
- TypedData_Get_Struct(self, struct cDataConverter_data, &cDataConverter_type, data);
1191
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
640
1192
  data->__offset = Qnil;
641
1193
  data->__condition = Qnil;
642
1194
  data->__type = Qnil;
643
1195
  data->__length = Qnil;
644
- data->__offset = cDataConverter_decode_seek_offset(self, field_data->offset, field_data->relative_offset);
645
- if (!data->__offset)
646
- return Qfalse;
647
- data->__condition = cDataConverter_decode_condition(self, field_data->condition);
1196
+ data->__condition = cStructure_decode_condition_ctx(self, ctx, field_data->condition);
648
1197
  if (!RTEST(data->__condition))
649
1198
  return Qfalse;
650
- data->__type = cDataConverter_decode_type(self, field_data->type);
651
- data->__length = cDataConverter_decode_length(self, field_data->length);
1199
+ data->__offset = cStructure_decode_seek_offset_ctx(self, ctx, field_data->offset, field_data->relative_offset, field_data->align, field_data->null_offset);
1200
+ if (data->__offset == Qfalse)
1201
+ return Qfalse;
1202
+ data->__type = cStructure_decode_type_ctx(self, ctx, field_data->type);
1203
+ data->__length = cStructure_decode_length_ctx(self, ctx, field_data->length);
652
1204
  return Qtrue;
653
1205
  }
654
1206
 
655
- /* def __restore_context
656
- @__iterator = nil
657
- @__type = nil
658
- @__length = nil
659
- @__count = nil
660
- @__offset = nil
661
- @__condition = nil
662
- end */
663
-
664
- static inline VALUE cDataConverter_restore_context(VALUE self) {
665
- struct cDataConverter_data *data;
666
- TypedData_Get_Struct(self, struct cDataConverter_data, &cDataConverter_type, data);
667
- data->__iterator = Qnil;
668
- data->__type = Qnil;
669
- data->__length = Qnil;
670
- data->__count = Qnil;
671
- data->__offset = Qnil;
672
- data->__condition = Qnil;
673
- return Qnil;
1207
+ static VALUE cStructure_decode_dynamic_conditions(VALUE self, VALUE field) {
1208
+ struct cStructure_data *data;
1209
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
1210
+ return cStructure_decode_dynamic_conditions_ctx(self, data->active_ctx, field);
674
1211
  }
675
1212
 
676
- /* def __convert_field(field)
677
- __decode_static_conditions(field)
678
- vs = @__count.times.collect do |it|
679
- @__iterator = it
680
- if __decode_dynamic_conditions(field)
681
- @__type::convert(@__input, @__output, @__input_big, @__output_big, self, it, @__length)
682
- else
683
- nil
684
- end
685
- end
686
- __restore_context
687
- vs = vs.first unless field.count
688
- vs
689
- end */
1213
+ /* Forward declarations for mutually recursive Structure <-> Field fast paths */
1214
+ static VALUE cStructure_load_fast(VALUE self, libbin_ctx_t *ctx, VALUE input_big, VALUE parent, VALUE index, uint32_t flags);
1215
+ static VALUE cStructure_dump_fast(VALUE self, libbin_ctx_t *ctx, VALUE output_big, VALUE parent, VALUE index, uint32_t flags);
1216
+ static VALUE cStructure_convert_fast(VALUE self, libbin_ctx_t *ctx, VALUE input_big, VALUE output_big, VALUE parent, VALUE index, uint32_t flags);
1217
+ static VALUE cStructure_singl_load_ctx(VALUE klass, libbin_ctx_t *ctx, VALUE input_big, VALUE parent, VALUE index, VALUE length, uint32_t flags);
1218
+ static VALUE cStructure_singl_dump_ctx(VALUE klass, VALUE value, libbin_ctx_t *ctx, VALUE output_big, VALUE parent, VALUE index, VALUE length, uint32_t flags);
1219
+ static VALUE cStructure_singl_convert_ctx(VALUE klass, libbin_ctx_t *ctx, VALUE input_big, VALUE output_big, VALUE parent, VALUE index, VALUE length, uint32_t flags);
690
1220
 
691
- static ID id_convert;
1221
+ static inline VALUE dispatch_type_load(
1222
+ VALUE self,
1223
+ struct cStructure_data *data,
1224
+ libbin_ctx_t *ctx,
1225
+ VALUE type,
1226
+ uint8_t known_scalar,
1227
+ uint8_t known_struct,
1228
+ VALUE iterator,
1229
+ VALUE length)
1230
+ {
1231
+ if (ctx && !LIBBIN_ATOMIC_LOAD(&libbin_scalar_overridden)) {
1232
+ libbin_scalar_kind_t sk = known_scalar ? (libbin_scalar_kind_t)known_scalar : libbin_lookup_scalar_kind(type);
1233
+ if (sk != SCALAR_NONE)
1234
+ return libbin_scalar_load_fast(sk, &ctx->in_io, RTEST(data->__input_big), length);
1235
+ }
1236
+ if (ctx && (known_struct || (RB_TYPE_P(type, T_CLASS) && RTEST(rb_class_inherited_p(type, cStructure))))) {
1237
+ uint32_t tflags = libbin_get_structure_flags(type);
1238
+ if (!(tflags & LIBBIN_OVR_SINGL_LOAD))
1239
+ return cStructure_singl_load_ctx(type, ctx, data->__input_big, self, iterator, length, tflags);
1240
+ }
1241
+ libbin_ctx_sync_to_ruby(ctx);
1242
+ VALUE res = rb_funcall(type, id_load, 5,
1243
+ data->__input,
1244
+ data->__input_big,
1245
+ self,
1246
+ iterator,
1247
+ length);
1248
+ libbin_ctx_sync_from_ruby(ctx);
1249
+ return res;
1250
+ }
692
1251
 
693
- static inline VALUE cDataConverter_convert_field(VALUE self, VALUE field) {
694
- VALUE res;
695
- struct cDataConverter_data *data;
1252
+ static inline void dispatch_type_dump(
1253
+ VALUE self,
1254
+ struct cStructure_data *data,
1255
+ libbin_ctx_t *ctx,
1256
+ VALUE type,
1257
+ uint8_t known_scalar,
1258
+ uint8_t known_struct,
1259
+ VALUE val,
1260
+ VALUE iterator,
1261
+ VALUE length)
1262
+ {
1263
+ if (ctx && !LIBBIN_ATOMIC_LOAD(&libbin_scalar_overridden)) {
1264
+ libbin_scalar_kind_t sk = known_scalar ? (libbin_scalar_kind_t)known_scalar : libbin_lookup_scalar_kind(type);
1265
+ if (sk != SCALAR_NONE) {
1266
+ libbin_scalar_dump_fast(sk, val, &ctx->out_io, RTEST(data->__output_big), length);
1267
+ return;
1268
+ }
1269
+ }
1270
+ if (ctx && (known_struct || (RB_TYPE_P(type, T_CLASS) && RTEST(rb_class_inherited_p(type, cStructure))))) {
1271
+ uint32_t tflags = libbin_get_structure_flags(type);
1272
+ if (!(tflags & LIBBIN_OVR_SINGL_DUMP)) {
1273
+ cStructure_singl_dump_ctx(type, val, ctx, data->__output_big, self, iterator, length, tflags);
1274
+ return;
1275
+ }
1276
+ }
1277
+ libbin_ctx_sync_to_ruby(ctx);
1278
+ rb_funcall(type, id_dump, 6,
1279
+ val,
1280
+ data->__output,
1281
+ data->__output_big,
1282
+ self,
1283
+ iterator,
1284
+ length);
1285
+ libbin_ctx_sync_from_ruby(ctx);
1286
+ }
1287
+
1288
+ static inline VALUE dispatch_type_convert(
1289
+ VALUE self,
1290
+ struct cStructure_data *data,
1291
+ libbin_ctx_t *ctx,
1292
+ VALUE type,
1293
+ uint8_t known_scalar,
1294
+ uint8_t known_struct,
1295
+ VALUE iterator,
1296
+ VALUE length)
1297
+ {
1298
+ if (ctx && !LIBBIN_ATOMIC_LOAD(&libbin_scalar_overridden)) {
1299
+ libbin_scalar_kind_t sk = known_scalar ? (libbin_scalar_kind_t)known_scalar : libbin_lookup_scalar_kind(type);
1300
+ if (sk != SCALAR_NONE)
1301
+ return libbin_scalar_convert_fast(sk, &ctx->in_io, &ctx->out_io, RTEST(data->__input_big), RTEST(data->__output_big), length);
1302
+ }
1303
+ if (ctx && (known_struct || (RB_TYPE_P(type, T_CLASS) && RTEST(rb_class_inherited_p(type, cStructure))))) {
1304
+ uint32_t tflags = libbin_get_structure_flags(type);
1305
+ if (!(tflags & LIBBIN_OVR_SINGL_CONVERT))
1306
+ return cStructure_singl_convert_ctx(type, ctx, data->__input_big, data->__output_big, self, iterator, length, tflags);
1307
+ }
1308
+ libbin_ctx_sync_to_ruby(ctx);
1309
+ VALUE res = rb_funcall(type, id_convert, 7,
1310
+ data->__input,
1311
+ data->__output,
1312
+ data->__input_big,
1313
+ data->__output_big,
1314
+ self,
1315
+ iterator,
1316
+ length);
1317
+ libbin_ctx_sync_from_ruby(ctx);
1318
+ return res;
1319
+ }
1320
+
1321
+ static inline VALUE cStructure_convert_field_ctx(VALUE self, libbin_ctx_t *ctx, VALUE field) {
1322
+ struct cStructure_data *data;
696
1323
  struct cField_data *field_data;
697
- if (NIL_P(cDataConverter_decode_static_conditions(self, field)))
698
- return Qnil;
699
- TypedData_Get_Struct(self, struct cDataConverter_data, &cDataConverter_type, data);
1324
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
700
1325
  TypedData_Get_Struct(field, struct cField_data, &cField_type, field_data);
701
1326
 
1327
+ if (field_data->is_static_simple && ctx) {
1328
+ return dispatch_type_convert(self, data, ctx, field_data->type,
1329
+ field_data->scalar_kind, field_data->type_is_struct, INT2FIX(0), field_data->length);
1330
+ }
1331
+
1332
+ if (NIL_P(cStructure_decode_static_conditions_ctx(self, ctx, field)))
1333
+ return Qnil;
1334
+
1335
+ VALUE res;
702
1336
  if (RTEST(field_data->count)) {
703
1337
  long count = NUM2LONG(data->__count);
1338
+ if (count < 0)
1339
+ rb_raise(rb_eArgError, "count must be non-negative: %ld", count);
704
1340
  res = rb_ary_new_capa(count);
705
1341
 
706
1342
  for (long i = 0; i < count; i++) {
707
1343
  data->__iterator = LONG2NUM(i);
708
- if (RTEST(cDataConverter_decode_dynamic_conditions(self, field)))
709
- rb_ary_store(res, i, rb_funcall(data->__type, id_convert, 7,
710
- data->__input,
711
- data->__output,
712
- data->__input_big,
713
- data->__output_big,
714
- self,
715
- data->__iterator,
716
- data->__length));
717
- else
1344
+ if (RTEST(cStructure_decode_dynamic_conditions_ctx(self, ctx, field))) {
1345
+ ptrdiff_t field_start = (!NIL_P(field_data->expect) && ctx && ctx->has_in) ? libbin_io_tell(&ctx->in_io) : -1;
1346
+ data->__value = dispatch_type_convert(self, data, ctx, data->__type,
1347
+ field_data->scalar_kind, field_data->type_is_struct, data->__iterator, data->__length);
1348
+ rb_ary_store(res, i,
1349
+ cStructure_decode_expect_ctx(self, ctx, field_data->expect, data->__value, field_start));
1350
+ } else
718
1351
  rb_ary_store(res, i, Qnil);
719
1352
  }
720
1353
  } else {
721
1354
  data->__iterator = INT2FIX(0);
722
- if (RTEST(cDataConverter_decode_dynamic_conditions(self, field)))
723
- res = rb_funcall(data->__type, id_convert, 7,
724
- data->__input,
725
- data->__output,
726
- data->__input_big,
727
- data->__output_big,
728
- self,
729
- data->__iterator,
730
- data->__length);
731
- else
1355
+ if (RTEST(cStructure_decode_dynamic_conditions_ctx(self, ctx, field))) {
1356
+ ptrdiff_t field_start = (!NIL_P(field_data->expect) && ctx && ctx->has_in) ? libbin_io_tell(&ctx->in_io) : -1;
1357
+ data->__value = dispatch_type_convert(self, data, ctx, data->__type,
1358
+ field_data->scalar_kind, field_data->type_is_struct, data->__iterator, data->__length);
1359
+ res = cStructure_decode_expect_ctx(self, ctx, field_data->expect, data->__value, field_start);
1360
+ } else
732
1361
  res = Qnil;
733
1362
  }
734
1363
 
735
- cDataConverter_restore_context(self);
1364
+ cStructure_restore_context(self);
736
1365
  return res;
737
1366
  }
738
1367
 
739
- /* def __load_field(field)
740
- __decode_static_conditions(field)
741
- vs = @__count.times.collect do |it|
742
- @__iterator = it
743
- if __decode_dynamic_conditions(field)
744
- @__type::load(@__input, @__input_big, self, it, @__length)
745
- else
746
- nil
747
- end
748
- end
749
- __restore_context
750
- vs = vs.first unless field.count
751
- vs
752
- end */
753
-
754
- static ID id_load;
1368
+ static VALUE cStructure_convert_field(VALUE self, VALUE field) {
1369
+ struct cStructure_data *data;
1370
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
1371
+ libbin_ctx_sync_from_ruby(data->active_ctx);
1372
+ VALUE res = cStructure_convert_field_ctx(self, data->active_ctx, field);
1373
+ libbin_ctx_sync_to_ruby(data->active_ctx);
1374
+ return res;
1375
+ }
755
1376
 
756
- static inline VALUE cDataConverter_load_field(VALUE self, VALUE field) {
757
- VALUE res;
758
- struct cDataConverter_data *data;
1377
+ static inline VALUE cStructure_load_field_ctx(VALUE self, libbin_ctx_t *ctx, VALUE field) {
1378
+ struct cStructure_data *data;
759
1379
  struct cField_data *field_data;
760
- if (NIL_P(cDataConverter_decode_static_conditions(self, field)))
761
- return Qnil;
762
- TypedData_Get_Struct(self, struct cDataConverter_data, &cDataConverter_type, data);
1380
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
763
1381
  TypedData_Get_Struct(field, struct cField_data, &cField_type, field_data);
764
1382
 
1383
+ if (field_data->is_static_simple && ctx) {
1384
+ return dispatch_type_load(self, data, ctx, field_data->type,
1385
+ field_data->scalar_kind, field_data->type_is_struct, INT2FIX(0), field_data->length);
1386
+ }
1387
+
1388
+ if (NIL_P(cStructure_decode_static_conditions_ctx(self, ctx, field)))
1389
+ return Qnil;
1390
+
1391
+ VALUE res;
765
1392
  if (RTEST(field_data->count)) {
766
1393
  long count = NUM2LONG(data->__count);
1394
+ if (count < 0)
1395
+ rb_raise(rb_eArgError, "count must be non-negative: %ld", count);
767
1396
  res = rb_ary_new_capa(count);
768
1397
 
769
1398
  for (long i = 0; i < count; i++) {
770
1399
  data->__iterator = LONG2NUM(i);
771
- if (RTEST(cDataConverter_decode_dynamic_conditions(self, field)))
772
- rb_ary_store(res, i, rb_funcall(data->__type, id_load, 5,
773
- data->__input,
774
- data->__input_big,
775
- self,
776
- data->__iterator,
777
- data->__length));
778
- else
1400
+ if (RTEST(cStructure_decode_dynamic_conditions_ctx(self, ctx, field))) {
1401
+ ptrdiff_t field_start = (!NIL_P(field_data->expect) && ctx && ctx->has_in) ? libbin_io_tell(&ctx->in_io) : -1;
1402
+ data->__value = dispatch_type_load(self, data, ctx, data->__type,
1403
+ field_data->scalar_kind, field_data->type_is_struct, data->__iterator, data->__length);
1404
+ rb_ary_store(res, i,
1405
+ cStructure_decode_expect_ctx(self, ctx, field_data->expect, data->__value, field_start));
1406
+ } else
779
1407
  rb_ary_store(res, i, Qnil);
780
1408
  }
781
1409
  } else {
782
1410
  data->__iterator = INT2FIX(0);
783
- if (RTEST(cDataConverter_decode_dynamic_conditions(self, field)))
784
- res = rb_funcall(data->__type, id_load, 5,
785
- data->__input,
786
- data->__input_big,
787
- self,
788
- data->__iterator,
789
- data->__length);
790
- else
1411
+ if (RTEST(cStructure_decode_dynamic_conditions_ctx(self, ctx, field))) {
1412
+ ptrdiff_t field_start = (!NIL_P(field_data->expect) && ctx && ctx->has_in) ? libbin_io_tell(&ctx->in_io) : -1;
1413
+ data->__value = dispatch_type_load(self, data, ctx, data->__type,
1414
+ field_data->scalar_kind, field_data->type_is_struct, data->__iterator, data->__length);
1415
+ res = cStructure_decode_expect_ctx(self, ctx, field_data->expect, data->__value, field_start);
1416
+ } else
791
1417
  res = Qnil;
792
1418
  }
793
- cDataConverter_restore_context(self);
1419
+ cStructure_restore_context(self);
794
1420
  return res;
795
1421
  }
796
1422
 
797
- /* def __dump_field(vs, field)
798
- __decode_static_conditions(field)
799
- vs = [vs] unless field.count
800
- vs.each_with_index do |v, it|
801
- @__iterator = it
802
- if __decode_dynamic_conditions(field)
803
- @__type::dump(v, @__output, @__output_big, self, it, @__length)
804
- end
805
- end
806
- __restore_context
807
- end */
808
-
809
- static ID id_dump;
1423
+ static VALUE cStructure_load_field(VALUE self, VALUE field) {
1424
+ struct cStructure_data *data;
1425
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
1426
+ libbin_ctx_sync_from_ruby(data->active_ctx);
1427
+ VALUE res = cStructure_load_field_ctx(self, data->active_ctx, field);
1428
+ libbin_ctx_sync_to_ruby(data->active_ctx);
1429
+ return res;
1430
+ }
810
1431
 
811
- static inline VALUE cDataConverter_dump_field(VALUE self, VALUE values, VALUE field) {
812
- struct cDataConverter_data *data;
1432
+ static inline VALUE cStructure_dump_field_ctx(VALUE self, libbin_ctx_t *ctx, VALUE values, VALUE field) {
1433
+ struct cStructure_data *data;
813
1434
  struct cField_data *field_data;
814
- if (NIL_P(cDataConverter_decode_static_conditions(self, field)))
815
- return Qnil;
816
- TypedData_Get_Struct(self, struct cDataConverter_data, &cDataConverter_type, data);
1435
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
817
1436
  TypedData_Get_Struct(field, struct cField_data, &cField_type, field_data);
818
1437
 
1438
+ if (field_data->is_static_simple && ctx) {
1439
+ dispatch_type_dump(self, data, ctx, field_data->type,
1440
+ field_data->scalar_kind, field_data->type_is_struct, values, INT2FIX(0), field_data->length);
1441
+ return Qnil;
1442
+ }
1443
+
1444
+ if (NIL_P(cStructure_decode_static_conditions_ctx(self, ctx, field)))
1445
+ return Qnil;
1446
+
819
1447
  if (RTEST(field_data->count)) {
820
- long count = RARRAY_LEN(values);
1448
+ long count = NUM2LONG(data->__count);
1449
+ if (count < 0)
1450
+ rb_raise(rb_eArgError, "count must be non-negative: %ld", count);
1451
+ if (!NIL_P(field_data->name) || !NIL_P(values)) {
1452
+ Check_Type(values, T_ARRAY);
1453
+ if (RARRAY_LEN(values) < count)
1454
+ rb_raise(rb_eArgError, "array too short for count: got %ld needed %ld", RARRAY_LEN(values), count);
1455
+ }
821
1456
 
822
1457
  for (long i = 0; i < count; i++) {
823
1458
  data->__iterator = LONG2NUM(i);
824
- if (RTEST(cDataConverter_decode_dynamic_conditions(self, field)))
825
- rb_funcall(data->__type, id_dump, 6,
826
- rb_ary_entry(values, i),
827
- data->__output,
828
- data->__output_big,
829
- self,
830
- data->__iterator,
831
- data->__length);
1459
+ if (RTEST(cStructure_decode_dynamic_conditions_ctx(self, ctx, field))) {
1460
+ ptrdiff_t field_start = (!NIL_P(field_data->expect) && ctx && ctx->has_out) ? libbin_io_tell(&ctx->out_io) : -1;
1461
+ data->__value = (NIL_P(field_data->name) && NIL_P(values)) ? Qnil : rb_ary_entry(values, i);
1462
+ cStructure_decode_expect_ctx(self, ctx, field_data->expect, data->__value, field_start);
1463
+ dispatch_type_dump(self, data, ctx, data->__type,
1464
+ field_data->scalar_kind, field_data->type_is_struct, data->__value, data->__iterator, data->__length);
1465
+ }
832
1466
  }
833
1467
  } else {
834
1468
  data->__iterator = INT2FIX(0);
835
- if (RTEST(cDataConverter_decode_dynamic_conditions(self, field)))
836
- rb_funcall(data->__type, id_dump, 6,
837
- values,
838
- data->__output,
839
- data->__output_big,
840
- self,
841
- data->__iterator,
842
- data->__length);
1469
+ if (RTEST(cStructure_decode_dynamic_conditions_ctx(self, ctx, field))) {
1470
+ ptrdiff_t field_start = (!NIL_P(field_data->expect) && ctx && ctx->has_out) ? libbin_io_tell(&ctx->out_io) : -1;
1471
+ data->__value = values;
1472
+ cStructure_decode_expect_ctx(self, ctx, field_data->expect, data->__value, field_start);
1473
+ dispatch_type_dump(self, data, ctx, data->__type,
1474
+ field_data->scalar_kind, field_data->type_is_struct, data->__value, data->__iterator, data->__length);
1475
+ }
843
1476
  }
844
- cDataConverter_restore_context(self);
1477
+ cStructure_restore_context(self);
845
1478
  return Qnil;
846
1479
  }
847
1480
 
848
- /* def __shape_field(vs, kind, field)
849
- __decode_static_conditions(field)
850
- vs = [vs] unless field.count
851
- vs = vs.each_with_index.collect do |v, it|
852
- @__iterator = it
853
- if __decode_dynamic_conditions(field)
854
- sh = @__type::shape(v, @__cur_position, self, it, kind, @__length)
855
- @__cur_position = sh.last + 1 if sh.last && sh.last >= 0
856
- sh
857
- end
858
- end
859
- __restore_context
860
- vs = field.count ? kind.new(vs) : vs.first
861
- vs
862
- end */
863
-
864
- static ID id_shape;
865
-
866
- static inline VALUE cDataConverter_shape_field(
1481
+ static VALUE cStructure_dump_field(VALUE self, VALUE values, VALUE field) {
1482
+ struct cStructure_data *data;
1483
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
1484
+ libbin_ctx_sync_from_ruby(data->active_ctx);
1485
+ VALUE res = cStructure_dump_field_ctx(self, data->active_ctx, values, field);
1486
+ libbin_ctx_sync_to_ruby(data->active_ctx);
1487
+ return res;
1488
+ }
1489
+
1490
+ static inline VALUE cStructure_shape_field(
867
1491
  VALUE self,
868
1492
  VALUE values,
869
1493
  VALUE kind,
870
1494
  VALUE field)
871
1495
  {
872
1496
  VALUE res = Qnil;
873
- struct cDataConverter_data *data;
1497
+ struct cStructure_data *data;
874
1498
  struct cField_data *field_data;
875
- if (NIL_P(cDataConverter_decode_static_conditions(self, field)))
1499
+ if (NIL_P(cStructure_decode_static_conditions_ctx(self, NULL, field)))
876
1500
  return Qnil;
877
- TypedData_Get_Struct(self, struct cDataConverter_data, &cDataConverter_type, data);
1501
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
878
1502
  TypedData_Get_Struct(field, struct cField_data, &cField_type, field_data);
879
1503
 
880
1504
  if (RTEST(field_data->count)) {
881
- long count = RARRAY_LEN(values);
1505
+ long count = NUM2LONG(data->__count);
1506
+ if (count < 0)
1507
+ rb_raise(rb_eArgError, "count must be non-negative: %ld", count);
1508
+ if (!NIL_P(field_data->name) || !NIL_P(values)) {
1509
+ Check_Type(values, T_ARRAY);
1510
+ if (RARRAY_LEN(values) < count)
1511
+ rb_raise(rb_eArgError, "array too short for count: got %ld needed %ld", RARRAY_LEN(values), count);
1512
+ }
882
1513
  res = rb_ary_new_capa(count);
883
1514
 
884
1515
  for (long i = 0; i < count; i++) {
885
1516
  data->__iterator = LONG2NUM(i);
886
- if (RTEST(cDataConverter_decode_dynamic_conditions(self, field))) {
1517
+ if (RTEST(cStructure_decode_dynamic_conditions_ctx(self, NULL, field))) {
1518
+ VALUE elem_val = (NIL_P(field_data->name) && NIL_P(values)) ? Qnil : rb_ary_entry(values, i);
887
1519
  VALUE shape = rb_funcall(data->__type, id_shape, 6,
888
- rb_ary_entry(values, i),
1520
+ elem_val,
889
1521
  data->__cur_position,
890
1522
  self,
891
1523
  data->__iterator,
892
1524
  kind,
893
1525
  data->__length);
894
1526
  rb_ary_store(res, i, shape);
895
- VALUE last = rb_funcall(shape, rb_intern("last"), 0);
896
- if (RTEST(last)) {
897
- ptrdiff_t pos = NUM2LL(last);
898
- if (pos >= 0)
899
- data->__cur_position = LL2NUM(pos + 1);
1527
+ if (!NIL_P(shape)) {
1528
+ VALUE last = rb_funcall(shape, id_last, 0);
1529
+ if (RTEST(last)) {
1530
+ ptrdiff_t pos = NUM2LL(last);
1531
+ if (pos >= 0)
1532
+ data->__cur_position = LL2NUM(pos + 1);
1533
+ }
900
1534
  }
901
1535
  }
902
1536
  }
903
1537
  res = rb_class_new_instance(1, &res, kind);
904
1538
  } else {
905
1539
  data->__iterator = INT2FIX(0);
906
- if (RTEST(cDataConverter_decode_dynamic_conditions(self, field))) {
1540
+ if (RTEST(cStructure_decode_dynamic_conditions_ctx(self, NULL, field))) {
907
1541
  res = rb_funcall(data->__type, id_shape, 6,
908
1542
  values,
909
1543
  data->__cur_position,
@@ -911,166 +1545,299 @@ static inline VALUE cDataConverter_shape_field(
911
1545
  data->__iterator,
912
1546
  kind,
913
1547
  data->__length);
914
- VALUE last = rb_funcall(res, rb_intern("last"), 0);
915
- if (RTEST(last)) {
916
- ptrdiff_t pos = NUM2LL(last);
917
- if (pos >= 0)
918
- data->__cur_position = LL2NUM(pos + 1);
1548
+ if (!NIL_P(res)) {
1549
+ VALUE last = rb_funcall(res, id_last, 0);
1550
+ if (RTEST(last)) {
1551
+ ptrdiff_t pos = NUM2LL(last);
1552
+ if (pos >= 0)
1553
+ data->__cur_position = LL2NUM(pos + 1);
1554
+ }
919
1555
  }
920
1556
  }
921
1557
  }
922
- cDataConverter_restore_context(self);
1558
+ cStructure_restore_context(self);
923
1559
  return res;
924
1560
  }
925
1561
 
926
- /* def __load_fields
927
- self.class.instance_variable_get(:@fields).each { |field|
928
- begin
929
- send("#{field.name}=", __load_field(field))
930
- rescue
931
- STDERR.puts "#{self.class}: #{field.name}(#{field.type})"
932
- raise
933
- end
934
- }
935
- self
936
- end */
937
-
938
- static ID id_fields;
939
-
940
1562
  struct fields_state {
941
1563
  VALUE self;
942
1564
  VALUE fields;
943
1565
  VALUE field;
944
1566
  };
945
1567
 
946
- static inline VALUE cDataConverter_fields_rescue(VALUE state_p, VALUE exception) {
1568
+ static VALUE cStructure_fields_rescue(VALUE state_p, VALUE exception) {
947
1569
  struct fields_state *state = (struct fields_state *)state_p;
948
- if (NIL_P(state->field)) {
949
- struct cDataConverter_data *data;
950
- TypedData_Get_Struct(state->self, struct cDataConverter_data, &cDataConverter_type, data);
951
- if (!NIL_P(rb_ivar_get(mLibBin, rb_intern("@__output"))))
952
- rb_funcall(rb_ivar_get(mLibBin, rb_intern("@__output")), rb_intern("print"), 6,
953
- rb_obj_class(state->self),
954
- rb_str_new_cstr(": could not load fields, index: "),
955
- data->__index,
956
- rb_str_new_cstr(", current position: "),
957
- data->__cur_position,
958
- rb_str_new_cstr("\n"));
959
- } else {
960
- struct cField_data *field_data;
961
- TypedData_Get_Struct(state->field, struct cField_data, &cField_type, field_data);
962
- if (!NIL_P(rb_ivar_get(mLibBin, rb_intern("@__output"))))
963
- rb_funcall(rb_ivar_get(mLibBin, rb_intern("@__output")), rb_intern("print"), 6,
964
- rb_obj_class(state->self),
965
- rb_str_new_cstr(": "),
966
- field_data->name,
967
- rb_str_new_cstr("("),
968
- field_data->type,
969
- rb_str_new_cstr(")\n"));
970
- }
1570
+ libbin_attach_error_context(exception, state->self, state->field, NULL, 0, Qnil);
1571
+ libbin_print_frame_error(state->self, state->field);
971
1572
  rb_exc_raise(exception);
972
1573
  return state->self;
973
1574
  }
974
1575
 
975
- static inline VALUE cDataConverter_load_fields_wrapper(VALUE state_p) {
976
- struct fields_state *state = (struct fields_state *)state_p;
977
- state->fields = rb_ivar_get(rb_obj_class(state->self), id_fields);
978
- for (long i = 0; i < RARRAY_LEN(state->fields); i++) {
979
- state->field = rb_ary_entry(state->fields, i);
980
- struct cField_data *field_data;
981
- TypedData_Get_Struct(state->field, struct cField_data, &cField_type, field_data);
982
- rb_funcall(state->self, field_data->setter, 1, cDataConverter_load_field(state->self, state->field));
1576
+ static void libbin_apply_stride(VALUE self, libbin_ctx_t *ctx, uint32_t flags, uint8_t mode, VALUE stride_expr) {
1577
+ long long stride_val = NUM2LL(cStructure_decode_expression_ctx(self, ctx, stride_expr));
1578
+ if (stride_val <= 0)
1579
+ return;
1580
+ struct cStructure_data *data;
1581
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
1582
+ ptrdiff_t start_pos = NUM2LL(data->__position);
1583
+ ptrdiff_t target = start_pos + (ptrdiff_t)stride_val;
1584
+ if (mode == 0) {
1585
+ ptrdiff_t cur = libbin_io_tell(&ctx->in_io);
1586
+ if (cur < target) {
1587
+ libbin_io_skip_read(&ctx->in_io, (size_t)(target - cur));
1588
+ } else if (cur > target) {
1589
+ if (!ctx->in_io.non_seekable && (flags & LIBBIN_HAS_OFFSET_FIELD))
1590
+ libbin_io_seek(&ctx->in_io, target);
1591
+ else
1592
+ rb_raise(eLibBinError, "structure %"PRIsVALUE" exceeded stride %lld (consumed %td bytes)",
1593
+ rb_obj_class(self), stride_val, cur - start_pos);
1594
+ }
1595
+ } else if (mode == 1) {
1596
+ ptrdiff_t cur = libbin_io_tell(&ctx->out_io);
1597
+ if (cur < target) {
1598
+ libbin_io_write_zeros(&ctx->out_io, (size_t)(target - cur));
1599
+ } else if (cur > target) {
1600
+ if (!ctx->out_io.non_seekable && (flags & LIBBIN_HAS_OFFSET_FIELD))
1601
+ libbin_io_seek(&ctx->out_io, target);
1602
+ else
1603
+ rb_raise(eLibBinError, "structure %"PRIsVALUE" exceeded stride %lld (consumed %td bytes)",
1604
+ rb_obj_class(self), stride_val, cur - start_pos);
1605
+ }
1606
+ } else {
1607
+ ptrdiff_t cur = libbin_io_tell(&ctx->in_io);
1608
+ if (cur < target) {
1609
+ libbin_copy_bytes(&ctx->in_io, &ctx->out_io, (size_t)(target - cur));
1610
+ } else if (cur > target) {
1611
+ if (!ctx->in_io.non_seekable && !ctx->out_io.non_seekable && (flags & LIBBIN_HAS_OFFSET_FIELD)) {
1612
+ libbin_io_seek(&ctx->in_io, target);
1613
+ libbin_io_seek(&ctx->out_io, target);
1614
+ } else {
1615
+ rb_raise(eLibBinError, "structure %"PRIsVALUE" exceeded stride %lld (consumed %td bytes)",
1616
+ rb_obj_class(self), stride_val, cur - start_pos);
1617
+ }
1618
+ }
983
1619
  }
984
- return state->self;
985
1620
  }
986
1621
 
987
- static ID id___load_fields;
988
-
989
- static inline VALUE cDataConverter_load_fields(VALUE self) {
990
- struct fields_state state = {self, Qnil, Qnil};
991
- rb_rescue(&cDataConverter_load_fields_wrapper, (VALUE)&state,
992
- &cDataConverter_fields_rescue, (VALUE)&state);
993
- return self;
1622
+ static inline void cStructure_load_fields_ctx(VALUE self, libbin_ctx_t *ctx, uint32_t flags) {
1623
+ VALUE klass = rb_obj_class(self);
1624
+ if (CLASS_OF(self) != klass) {
1625
+ flags |= LIBBIN_OVR_ACCESSORS | LIBBIN_OVR_LOAD_FIELD;
1626
+ flags &= ~LIBBIN_ALL_SCALAR_LEAF;
1627
+ }
1628
+ VALUE fields = rb_attr_get(klass, id_fields);
1629
+ int use_ivar = !(flags & LIBBIN_OVR_ACCESSORS);
1630
+ int use_fast_field = !(flags & LIBBIN_OVR_LOAD_FIELD);
1631
+
1632
+ VALUE fidx = ctx->pending_index;
1633
+ ctx->pending_index = Qnil;
1634
+ size_t depth = libbin_ctx_push_frame(ctx, self, 0, fidx);
1635
+ for (long i = 0; i < RARRAY_LEN(fields); i++) {
1636
+ VALUE field = rb_ary_entry(fields, i);
1637
+ if (depth < LIBBIN_MAX_FRAMES)
1638
+ ctx->frames[depth].field = field;
1639
+ struct cField_data *field_data;
1640
+ TypedData_Get_Struct(field, struct cField_data, &cField_type, field_data);
1641
+ VALUE val;
1642
+ if (use_fast_field) {
1643
+ val = cStructure_load_field_ctx(self, ctx, field);
1644
+ } else {
1645
+ libbin_ctx_sync_to_ruby(ctx);
1646
+ val = rb_funcall(self, id___load_field, 1, field);
1647
+ libbin_ctx_sync_from_ruby(ctx);
1648
+ }
1649
+ if (!NIL_P(field_data->name)) {
1650
+ if (use_ivar) {
1651
+ rb_ivar_set(self, field_data->ivar, val);
1652
+ } else {
1653
+ libbin_ctx_sync_to_ruby(ctx);
1654
+ rb_funcall(self, field_data->setter, 1, val);
1655
+ libbin_ctx_sync_from_ruby(ctx);
1656
+ }
1657
+ }
1658
+ }
1659
+ if (flags & LIBBIN_HAS_STRIDE) {
1660
+ VALUE stride = rb_attr_get(klass, id_stride);
1661
+ if (RTEST(stride))
1662
+ libbin_apply_stride(self, ctx, flags, 0, stride);
1663
+ }
1664
+ libbin_ctx_pop_frame(ctx, depth);
994
1665
  }
995
1666
 
996
- /* def __dump_fields
997
- self.class.instance_variable_get(:@fields).each { |field|
998
- begin
999
- __dump_field(send(field.name), field)
1000
- rescue
1001
- STDERR.puts "#{self.class}: #{field.name}(#{field.type})"
1002
- raise
1003
- end
1004
- }
1005
- self
1006
- end */
1667
+ static inline void cStructure_dump_fields_ctx(VALUE self, libbin_ctx_t *ctx, uint32_t flags) {
1668
+ VALUE klass = rb_obj_class(self);
1669
+ if (CLASS_OF(self) != klass) {
1670
+ flags |= LIBBIN_OVR_ACCESSORS | LIBBIN_OVR_DUMP_FIELD;
1671
+ flags &= ~LIBBIN_ALL_SCALAR_LEAF;
1672
+ }
1673
+ VALUE fields = rb_attr_get(klass, id_fields);
1674
+ int use_ivar = !(flags & LIBBIN_OVR_ACCESSORS);
1675
+ int use_fast_field = !(flags & LIBBIN_OVR_DUMP_FIELD);
1676
+
1677
+ VALUE fidx = ctx->pending_index;
1678
+ ctx->pending_index = Qnil;
1679
+ size_t depth = libbin_ctx_push_frame(ctx, self, 1, fidx);
1680
+ for (long i = 0; i < RARRAY_LEN(fields); i++) {
1681
+ VALUE field = rb_ary_entry(fields, i);
1682
+ if (depth < LIBBIN_MAX_FRAMES)
1683
+ ctx->frames[depth].field = field;
1684
+ struct cField_data *field_data;
1685
+ TypedData_Get_Struct(field, struct cField_data, &cField_type, field_data);
1686
+ VALUE val;
1687
+ if (NIL_P(field_data->name)) {
1688
+ val = Qnil;
1689
+ } else if (use_ivar) {
1690
+ val = rb_ivar_get(self, field_data->ivar);
1691
+ } else {
1692
+ libbin_ctx_sync_to_ruby(ctx);
1693
+ val = rb_funcall(self, field_data->getter, 0);
1694
+ libbin_ctx_sync_from_ruby(ctx);
1695
+ }
1696
+ if (use_fast_field) {
1697
+ cStructure_dump_field_ctx(self, ctx, val, field);
1698
+ } else {
1699
+ libbin_ctx_sync_to_ruby(ctx);
1700
+ rb_funcall(self, id___dump_field, 2, val, field);
1701
+ libbin_ctx_sync_from_ruby(ctx);
1702
+ }
1703
+ }
1704
+ if (flags & LIBBIN_HAS_STRIDE) {
1705
+ VALUE stride = rb_attr_get(klass, id_stride);
1706
+ if (RTEST(stride))
1707
+ libbin_apply_stride(self, ctx, flags, 1, stride);
1708
+ }
1709
+ libbin_ctx_pop_frame(ctx, depth);
1710
+ }
1007
1711
 
1008
- static inline VALUE cDataConverter_dump_fields_wrapper(VALUE state_p) {
1009
- struct fields_state *state = (struct fields_state *)state_p;
1010
- state->fields = rb_ivar_get(rb_obj_class(state->self), id_fields);
1011
- for (long i = 0; i < RARRAY_LEN(state->fields); i++) {
1012
- state->field = rb_ary_entry(state->fields, i);
1712
+ static inline void cStructure_convert_fields_ctx(VALUE self, libbin_ctx_t *ctx, uint32_t flags) {
1713
+ VALUE klass = rb_obj_class(self);
1714
+ if (CLASS_OF(self) != klass) {
1715
+ flags |= LIBBIN_OVR_ACCESSORS | LIBBIN_OVR_CONVERT_FIELD;
1716
+ flags &= ~LIBBIN_ALL_SCALAR_LEAF;
1717
+ }
1718
+ VALUE fields = rb_attr_get(klass, id_fields);
1719
+ int use_ivar = !(flags & LIBBIN_OVR_ACCESSORS);
1720
+ int use_fast_field = !(flags & LIBBIN_OVR_CONVERT_FIELD);
1721
+
1722
+ VALUE fidx = ctx->pending_index;
1723
+ ctx->pending_index = Qnil;
1724
+ size_t depth = libbin_ctx_push_frame(ctx, self, 2, fidx);
1725
+ for (long i = 0; i < RARRAY_LEN(fields); i++) {
1726
+ VALUE field = rb_ary_entry(fields, i);
1727
+ if (depth < LIBBIN_MAX_FRAMES)
1728
+ ctx->frames[depth].field = field;
1013
1729
  struct cField_data *field_data;
1014
- TypedData_Get_Struct(state->field, struct cField_data, &cField_type, field_data);
1015
- cDataConverter_dump_field(state->self, rb_funcall(state->self, field_data->getter, 0), state->field);
1730
+ TypedData_Get_Struct(field, struct cField_data, &cField_type, field_data);
1731
+ VALUE val;
1732
+ if (use_fast_field) {
1733
+ val = cStructure_convert_field_ctx(self, ctx, field);
1734
+ } else {
1735
+ libbin_ctx_sync_to_ruby(ctx);
1736
+ val = rb_funcall(self, id___convert_field, 1, field);
1737
+ libbin_ctx_sync_from_ruby(ctx);
1738
+ }
1739
+ if (!NIL_P(field_data->name)) {
1740
+ if (use_ivar) {
1741
+ rb_ivar_set(self, field_data->ivar, val);
1742
+ } else {
1743
+ libbin_ctx_sync_to_ruby(ctx);
1744
+ rb_funcall(self, field_data->setter, 1, val);
1745
+ libbin_ctx_sync_from_ruby(ctx);
1746
+ }
1747
+ }
1016
1748
  }
1017
- return state->self;
1749
+ if (flags & LIBBIN_HAS_STRIDE) {
1750
+ VALUE stride = rb_attr_get(klass, id_stride);
1751
+ if (RTEST(stride))
1752
+ libbin_apply_stride(self, ctx, flags, 2, stride);
1753
+ }
1754
+ libbin_ctx_pop_frame(ctx, depth);
1018
1755
  }
1019
1756
 
1020
- static ID id___dump_fields;
1757
+ struct top_fields_args {
1758
+ VALUE self;
1759
+ libbin_ctx_t *ctx;
1760
+ uint32_t flags;
1761
+ uint8_t mode;
1762
+ };
1021
1763
 
1022
- static inline VALUE cDataConverter_dump_fields(VALUE self) {
1023
- struct fields_state state = {self, Qnil, Qnil};
1024
- rb_rescue(&cDataConverter_dump_fields_wrapper, (VALUE)&state,
1025
- &cDataConverter_fields_rescue, (VALUE)&state);
1026
- return self;
1764
+ static VALUE top_fields_body(VALUE args_p) {
1765
+ struct top_fields_args *a = (struct top_fields_args *)args_p;
1766
+ if (a->mode == 0)
1767
+ cStructure_load_fields_ctx(a->self, a->ctx, a->flags);
1768
+ else if (a->mode == 1)
1769
+ cStructure_dump_fields_ctx(a->self, a->ctx, a->flags);
1770
+ else
1771
+ cStructure_convert_fields_ctx(a->self, a->ctx, a->flags);
1772
+ return a->self;
1027
1773
  }
1028
1774
 
1029
- /* def __convert_fields
1030
- self.class.instance_variable_get(:@fields).each { |field|
1031
- begin
1032
- send("#{field.name}=", __convert_field(field))
1033
- rescue
1034
- STDERR.puts "#{self.class}: #{field.name}(#{field.type})"
1035
- raise
1036
- end
1037
- }
1038
- self
1039
- end */
1775
+ static VALUE top_fields_rescue_wrapper(VALUE args_p) {
1776
+ struct top_fields_args *a = (struct top_fields_args *)args_p;
1777
+ return rb_rescue(top_fields_body, args_p, libbin_ctx_rescue, (VALUE)a->ctx);
1778
+ }
1040
1779
 
1041
- static inline VALUE cDataConverter_convert_fields_wrapper(VALUE state_p) {
1042
- struct fields_state *state = (struct fields_state *)state_p;
1043
- state->fields = rb_ivar_get(rb_obj_class(state->self), id_fields);
1044
- for (long i = 0; i < RARRAY_LEN(state->fields); i++) {
1045
- state->field = rb_ary_entry(state->fields, i);
1046
- struct cField_data *field_data;
1047
- TypedData_Get_Struct(state->field, struct cField_data, &cField_type, field_data);
1048
- rb_funcall(state->self, field_data->setter, 1, cDataConverter_convert_field(state->self, state->field));
1049
- }
1050
- return state->self;
1780
+ static VALUE top_fields_ensure(VALUE args_p) {
1781
+ struct top_fields_args *a = (struct top_fields_args *)args_p;
1782
+ struct cStructure_data *data;
1783
+ TypedData_Get_Struct(a->self, struct cStructure_data, &cStructure_type, data);
1784
+ data->active_ctx = NULL;
1785
+ return libbin_ctx_ensure((VALUE)a->ctx);
1051
1786
  }
1052
1787
 
1053
- static ID id___convert_fields;
1788
+ static VALUE cStructure_load_fields(VALUE self) {
1789
+ struct cStructure_data *data;
1790
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
1791
+ uint32_t flags = libbin_get_structure_flags(rb_obj_class(self));
1792
+ if (data->active_ctx) {
1793
+ libbin_ctx_sync_from_ruby(data->active_ctx);
1794
+ cStructure_load_fields_ctx(self, data->active_ctx, flags);
1795
+ libbin_ctx_sync_to_ruby(data->active_ctx);
1796
+ return self;
1797
+ }
1798
+ libbin_ctx_t ctx;
1799
+ libbin_ctx_init_load(&ctx, data->__input);
1800
+ data->active_ctx = &ctx;
1801
+ struct top_fields_args args = { self, &ctx, flags, 0 };
1802
+ rb_ensure(top_fields_rescue_wrapper, (VALUE)&args, top_fields_ensure, (VALUE)&args);
1803
+ return self;
1804
+ }
1054
1805
 
1055
- static inline VALUE cDataConverter_convert_fields(VALUE self) {
1056
- struct fields_state state = {self, Qnil, Qnil};
1057
- rb_rescue(&cDataConverter_convert_fields_wrapper, (VALUE)&state,
1058
- &cDataConverter_fields_rescue, (VALUE)&state);
1806
+ static VALUE cStructure_dump_fields(VALUE self) {
1807
+ struct cStructure_data *data;
1808
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
1809
+ uint32_t flags = libbin_get_structure_flags(rb_obj_class(self));
1810
+ if (data->active_ctx) {
1811
+ libbin_ctx_sync_from_ruby(data->active_ctx);
1812
+ cStructure_dump_fields_ctx(self, data->active_ctx, flags);
1813
+ libbin_ctx_sync_to_ruby(data->active_ctx);
1814
+ return self;
1815
+ }
1816
+ libbin_ctx_t ctx;
1817
+ libbin_ctx_init_dump(&ctx, data->__output);
1818
+ data->active_ctx = &ctx;
1819
+ struct top_fields_args args = { self, &ctx, flags, 1 };
1820
+ rb_ensure(top_fields_rescue_wrapper, (VALUE)&args, top_fields_ensure, (VALUE)&args);
1059
1821
  return self;
1060
1822
  }
1061
1823
 
1062
- /* def __shape_fields
1063
- members = {}
1064
- self.class.instance_variable_get(:@fields).each { |field|
1065
- begin
1066
- members[field.name] = __shape_field(send(field.name), kind, field)
1067
- rescue
1068
- STDERR.puts "#{self.class}: #{field.name}(#{field.type})"
1069
- raise
1070
- end
1071
- }
1072
- return members
1073
- end */
1824
+ static VALUE cStructure_convert_fields(VALUE self) {
1825
+ struct cStructure_data *data;
1826
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
1827
+ uint32_t flags = libbin_get_structure_flags(rb_obj_class(self));
1828
+ if (data->active_ctx) {
1829
+ libbin_ctx_sync_from_ruby(data->active_ctx);
1830
+ cStructure_convert_fields_ctx(self, data->active_ctx, flags);
1831
+ libbin_ctx_sync_to_ruby(data->active_ctx);
1832
+ return self;
1833
+ }
1834
+ libbin_ctx_t ctx;
1835
+ libbin_ctx_init_convert(&ctx, data->__input, data->__output);
1836
+ data->active_ctx = &ctx;
1837
+ struct top_fields_args args = { self, &ctx, flags, 2 };
1838
+ rb_ensure(top_fields_rescue_wrapper, (VALUE)&args, top_fields_ensure, (VALUE)&args);
1839
+ return self;
1840
+ }
1074
1841
 
1075
1842
  struct shape_fields_state {
1076
1843
  VALUE self;
@@ -1079,240 +1846,735 @@ struct shape_fields_state {
1079
1846
  VALUE kind;
1080
1847
  };
1081
1848
 
1082
- static inline VALUE cDataConverter_shape_fields_wrapper(VALUE state_p) {
1849
+ static VALUE cStructure_shape_fields_wrapper(VALUE state_p) {
1083
1850
  struct shape_fields_state *state = (struct shape_fields_state *)state_p;
1084
- state->fields = rb_ivar_get(rb_obj_class(state->self), id_fields);
1851
+ state->fields = rb_attr_get(rb_obj_class(state->self), id_fields);
1085
1852
  VALUE members = rb_hash_new();
1086
1853
  for (long i = 0; i < RARRAY_LEN(state->fields); i++) {
1087
1854
  state->field = rb_ary_entry(state->fields, i);
1088
1855
  struct cField_data *field_data;
1089
1856
  TypedData_Get_Struct(state->field, struct cField_data, &cField_type, field_data);
1090
- rb_hash_aset(members, ID2SYM(field_data->getter), cDataConverter_shape_field(state->self, rb_funcall(state->self, field_data->getter, 0), state->kind, state->field));
1857
+ if (NIL_P(field_data->name)) {
1858
+ VALUE sh = rb_funcall(state->self, id___shape_field, 3, Qnil, state->kind, state->field);
1859
+ if (!NIL_P(sh)) {
1860
+ VALUE pad_key = ID2SYM(rb_intern_str(rb_sprintf("__pad_%ld", i)));
1861
+ rb_hash_aset(members, pad_key, sh);
1862
+ }
1863
+ } else {
1864
+ rb_hash_aset(members, ID2SYM(field_data->getter),
1865
+ rb_funcall(state->self, id___shape_field, 3, rb_funcall(state->self, field_data->getter, 0), state->kind, state->field));
1866
+ }
1091
1867
  }
1092
1868
  return members;
1093
1869
  }
1094
1870
 
1095
- static ID id___shape_fields;
1096
-
1097
- static inline VALUE cDataConverter_shape_fields(VALUE self, VALUE kind) {
1871
+ static VALUE cStructure_shape_fields(VALUE self, VALUE kind) {
1098
1872
  struct shape_fields_state state = {self, Qnil, Qnil, kind};
1099
- return rb_rescue(&cDataConverter_shape_fields_wrapper, (VALUE)&state,
1100
- &cDataConverter_fields_rescue, (VALUE)&state);
1873
+ return rb_rescue(&cStructure_shape_fields_wrapper, (VALUE)&state,
1874
+ &cStructure_fields_rescue, (VALUE)&state);
1875
+ }
1876
+
1877
+ static VALUE cStructure_load_fast(VALUE self, libbin_ctx_t *ctx, VALUE input_big, VALUE parent, VALUE index, uint32_t flags) {
1878
+ VALUE klass = rb_obj_class(self);
1879
+ if (CLASS_OF(self) != klass)
1880
+ flags = ~0u;
1881
+ if ((flags & LIBBIN_ALL_SCALAR_LEAF) && !(flags & LIBBIN_FAST_LOAD_MASK) && !LIBBIN_ATOMIC_LOAD(&libbin_scalar_overridden)) {
1882
+ VALUE fields = rb_attr_get(klass, id_fields);
1883
+ int ibig = RTEST(input_big);
1884
+ VALUE fidx = !NIL_P(index) ? index : ctx->pending_index;
1885
+ ctx->pending_index = Qnil;
1886
+ size_t depth = libbin_ctx_push_frame(ctx, self, 0, fidx);
1887
+ for (long i = 0; i < RARRAY_LEN(fields); i++) {
1888
+ VALUE field = rb_ary_entry(fields, i);
1889
+ if (depth < LIBBIN_MAX_FRAMES)
1890
+ ctx->frames[depth].field = field;
1891
+ struct cField_data *fd;
1892
+ TypedData_Get_Struct(field, struct cField_data, &cField_type, fd);
1893
+ VALUE val = libbin_scalar_load_fast((libbin_scalar_kind_t)fd->scalar_kind, &ctx->in_io, ibig, fd->length);
1894
+ if (!NIL_P(fd->name))
1895
+ rb_ivar_set(self, fd->ivar, val);
1896
+ }
1897
+ libbin_ctx_pop_frame(ctx, depth);
1898
+ return self;
1899
+ }
1900
+ if (!(flags & (LIBBIN_OVR_SET_LOAD | LIBBIN_OVR_LOAD_FIELDS))) {
1901
+ struct cStructure_data *data;
1902
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
1903
+ if (!NIL_P(index))
1904
+ ctx->pending_index = index;
1905
+ data->__input = ctx->in_io.io;
1906
+ data->__input_big = input_big;
1907
+ data->__parent = parent;
1908
+ data->__index = index;
1909
+ data->__position = LL2NUM(libbin_io_tell(&ctx->in_io));
1910
+ data->__cur_position = data->__position;
1911
+ data->active_ctx = ctx;
1912
+ cStructure_load_fields_ctx(self, ctx, flags);
1913
+ libbin_unset_frame_state(self, 0);
1914
+ return self;
1915
+ }
1916
+ libbin_ctx_sync_to_ruby(ctx);
1917
+ rb_funcall(self, id___load, 4, ctx->in_io.io, input_big, parent, index);
1918
+ libbin_ctx_sync_from_ruby(ctx);
1919
+ return self;
1920
+ }
1921
+
1922
+ static VALUE cStructure_dump_fast(VALUE self, libbin_ctx_t *ctx, VALUE output_big, VALUE parent, VALUE index, uint32_t flags) {
1923
+ VALUE klass = rb_obj_class(self);
1924
+ if (CLASS_OF(self) != klass)
1925
+ flags = ~0u;
1926
+ if ((flags & LIBBIN_ALL_SCALAR_LEAF) && !(flags & LIBBIN_FAST_DUMP_MASK) && !LIBBIN_ATOMIC_LOAD(&libbin_scalar_overridden)) {
1927
+ VALUE fields = rb_attr_get(klass, id_fields);
1928
+ int obig = RTEST(output_big);
1929
+ VALUE fidx = !NIL_P(index) ? index : ctx->pending_index;
1930
+ ctx->pending_index = Qnil;
1931
+ size_t depth = libbin_ctx_push_frame(ctx, self, 1, fidx);
1932
+ for (long i = 0; i < RARRAY_LEN(fields); i++) {
1933
+ VALUE field = rb_ary_entry(fields, i);
1934
+ if (depth < LIBBIN_MAX_FRAMES)
1935
+ ctx->frames[depth].field = field;
1936
+ struct cField_data *fd;
1937
+ TypedData_Get_Struct(field, struct cField_data, &cField_type, fd);
1938
+ VALUE val = NIL_P(fd->name) ? Qnil : rb_ivar_get(self, fd->ivar);
1939
+ libbin_scalar_dump_fast((libbin_scalar_kind_t)fd->scalar_kind, val, &ctx->out_io, obig, fd->length);
1940
+ }
1941
+ libbin_ctx_pop_frame(ctx, depth);
1942
+ return self;
1943
+ }
1944
+ if (!(flags & (LIBBIN_OVR_SET_DUMP | LIBBIN_OVR_DUMP_FIELDS))) {
1945
+ struct cStructure_data *data;
1946
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
1947
+ if (!NIL_P(index))
1948
+ ctx->pending_index = index;
1949
+ data->__output = ctx->out_io.io;
1950
+ data->__output_big = output_big;
1951
+ data->__parent = parent;
1952
+ data->__index = index;
1953
+ data->__position = LL2NUM(libbin_io_tell(&ctx->out_io));
1954
+ data->__cur_position = data->__position;
1955
+ data->active_ctx = ctx;
1956
+ cStructure_dump_fields_ctx(self, ctx, flags);
1957
+ libbin_unset_frame_state(self, 1);
1958
+ return self;
1959
+ }
1960
+ libbin_ctx_sync_to_ruby(ctx);
1961
+ rb_funcall(self, id___dump, 4, ctx->out_io.io, output_big, parent, index);
1962
+ libbin_ctx_sync_from_ruby(ctx);
1963
+ return self;
1101
1964
  }
1102
1965
 
1103
- /* def __load(input, input_big, parent = nil, index = nil)
1104
- __set_load_type(input, input_big, parent, index)
1105
- __load_fields
1106
- __unset_load_type
1107
- self
1108
- end */
1966
+ static VALUE cStructure_convert_fast(VALUE self, libbin_ctx_t *ctx, VALUE input_big, VALUE output_big, VALUE parent, VALUE index, uint32_t flags) {
1967
+ VALUE klass = rb_obj_class(self);
1968
+ if (CLASS_OF(self) != klass)
1969
+ flags = ~0u;
1970
+ if ((flags & LIBBIN_ALL_SCALAR_LEAF) && !(flags & LIBBIN_FAST_CONVERT_MASK) && !LIBBIN_ATOMIC_LOAD(&libbin_scalar_overridden)) {
1971
+ VALUE fields = rb_attr_get(klass, id_fields);
1972
+ int ibig = RTEST(input_big);
1973
+ int obig = RTEST(output_big);
1974
+ VALUE fidx = !NIL_P(index) ? index : ctx->pending_index;
1975
+ ctx->pending_index = Qnil;
1976
+ size_t depth = libbin_ctx_push_frame(ctx, self, 2, fidx);
1977
+ for (long i = 0; i < RARRAY_LEN(fields); i++) {
1978
+ VALUE field = rb_ary_entry(fields, i);
1979
+ if (depth < LIBBIN_MAX_FRAMES)
1980
+ ctx->frames[depth].field = field;
1981
+ struct cField_data *fd;
1982
+ TypedData_Get_Struct(field, struct cField_data, &cField_type, fd);
1983
+ VALUE val = libbin_scalar_convert_fast((libbin_scalar_kind_t)fd->scalar_kind, &ctx->in_io, &ctx->out_io, ibig, obig, fd->length);
1984
+ if (!NIL_P(fd->name))
1985
+ rb_ivar_set(self, fd->ivar, val);
1986
+ }
1987
+ libbin_ctx_pop_frame(ctx, depth);
1988
+ return self;
1989
+ }
1990
+ if (!(flags & (LIBBIN_OVR_SET_CONVERT | LIBBIN_OVR_CONVERT_FIELDS))) {
1991
+ struct cStructure_data *data;
1992
+ TypedData_Get_Struct(self, struct cStructure_data, &cStructure_type, data);
1993
+ if (!NIL_P(index))
1994
+ ctx->pending_index = index;
1995
+ data->__input = ctx->in_io.io;
1996
+ data->__output = ctx->out_io.io;
1997
+ data->__input_big = input_big;
1998
+ data->__output_big = output_big;
1999
+ data->__parent = parent;
2000
+ data->__index = index;
2001
+ data->__position = LL2NUM(libbin_io_tell(&ctx->in_io));
2002
+ data->__cur_position = data->__position;
2003
+ data->active_ctx = ctx;
2004
+ cStructure_convert_fields_ctx(self, ctx, flags);
2005
+ libbin_unset_frame_state(self, 2);
2006
+ return self;
2007
+ }
2008
+ libbin_ctx_sync_to_ruby(ctx);
2009
+ rb_funcall(self, id___convert, 6, ctx->in_io.io, ctx->out_io.io, input_big, output_big, parent, index);
2010
+ libbin_ctx_sync_from_ruby(ctx);
2011
+ return self;
2012
+ }
2013
+
2014
+ static VALUE cStructure_load_body(VALUE self) {
2015
+ return rb_funcall(self, id___load_fields, 0);
2016
+ }
1109
2017
 
1110
- static ID id___load;
2018
+ static VALUE cStructure_load_ensure(VALUE self) {
2019
+ return rb_funcall(self, id___unset_load_state, 0);
2020
+ }
1111
2021
 
1112
- static inline VALUE cDataConverter_load(int argc, VALUE *argv, VALUE self) {
1113
- VALUE input;
2022
+ struct top_inst_args {
2023
+ VALUE self;
2024
+ libbin_ctx_t *ctx;
1114
2025
  VALUE input_big;
2026
+ VALUE output_big;
1115
2027
  VALUE parent;
1116
2028
  VALUE index;
2029
+ uint32_t flags;
2030
+ uint8_t mode;
2031
+ };
2032
+
2033
+ static VALUE top_inst_body(VALUE args_p) {
2034
+ struct top_inst_args *a = (struct top_inst_args *)args_p;
2035
+ if (a->mode == 0)
2036
+ return cStructure_load_fast(a->self, a->ctx, a->input_big, a->parent, a->index, a->flags);
2037
+ else if (a->mode == 1)
2038
+ return cStructure_dump_fast(a->self, a->ctx, a->output_big, a->parent, a->index, a->flags);
2039
+ else
2040
+ return cStructure_convert_fast(a->self, a->ctx, a->input_big, a->output_big, a->parent, a->index, a->flags);
2041
+ }
2042
+
2043
+ static VALUE top_inst_rescue_wrapper(VALUE args_p) {
2044
+ struct top_inst_args *a = (struct top_inst_args *)args_p;
2045
+ return rb_rescue(top_inst_body, args_p, libbin_ctx_rescue, (VALUE)a->ctx);
2046
+ }
2047
+
2048
+ static VALUE cStructure_load(int argc, VALUE *argv, VALUE self) {
2049
+ VALUE input, input_big, parent, index;
1117
2050
  rb_scan_args(argc, argv, "22", &input, &input_big, &parent, &index);
1118
- cDataConverter_set_load_type(self, input, input_big, parent, index);
1119
- rb_funcall(self, id___load_fields, 0);
1120
- cDataConverter_unset_load_type(self);
2051
+ uint32_t flags = (CLASS_OF(self) == rb_obj_class(self)) ? libbin_get_structure_flags(rb_obj_class(self)) : ~0u;
2052
+ if (!(flags & (LIBBIN_OVR_SET_LOAD | LIBBIN_OVR_LOAD_FIELDS))) {
2053
+ libbin_ctx_t *pctx = libbin_ctx_from_parent(parent, input, Qnil, 0);
2054
+ if (pctx) {
2055
+ libbin_ctx_sync_from_ruby(pctx);
2056
+ cStructure_load_fast(self, pctx, input_big, parent, index, flags);
2057
+ libbin_ctx_sync_to_ruby(pctx);
2058
+ return self;
2059
+ }
2060
+ libbin_ctx_t ctx;
2061
+ libbin_ctx_init_load(&ctx, input);
2062
+ struct top_inst_args args = { self, &ctx, input_big, Qnil, parent, index, flags, 0 };
2063
+ rb_ensure(top_inst_rescue_wrapper, (VALUE)&args, libbin_ctx_ensure, (VALUE)&ctx);
2064
+ return self;
2065
+ }
2066
+ rb_funcall(self, id___set_load_state, 4, input, input_big, parent, index);
2067
+ rb_ensure(cStructure_load_body, self, cStructure_load_ensure, self);
1121
2068
  return self;
1122
2069
  }
1123
2070
 
1124
- /* def __dump(output, output_big, parent = nil, index = nil)
1125
- __set_dump_type(output, output_big, parent, index)
1126
- __dump_fields
1127
- __unset_dump_type
1128
- self
1129
- end */
2071
+ static VALUE cStructure_dump_body(VALUE self) {
2072
+ return rb_funcall(self, id___dump_fields, 0);
2073
+ }
1130
2074
 
1131
- static ID id___dump;
2075
+ static VALUE cStructure_dump_ensure(VALUE self) {
2076
+ return rb_funcall(self, id___unset_dump_state, 0);
2077
+ }
1132
2078
 
1133
- static inline VALUE cDataConverter_dump(int argc, VALUE *argv, VALUE self) {
1134
- VALUE output;
1135
- VALUE output_big;
1136
- VALUE parent;
1137
- VALUE index;
2079
+ static VALUE cStructure_dump(int argc, VALUE *argv, VALUE self) {
2080
+ VALUE output, output_big, parent, index;
1138
2081
  rb_scan_args(argc, argv, "22", &output, &output_big, &parent, &index);
1139
- cDataConverter_set_dump_type(self, output, output_big, parent, index);
1140
- rb_funcall(self, id___dump_fields, 0);
1141
- cDataConverter_unset_dump_type(self);
2082
+ uint32_t flags = (CLASS_OF(self) == rb_obj_class(self)) ? libbin_get_structure_flags(rb_obj_class(self)) : ~0u;
2083
+ if (!(flags & (LIBBIN_OVR_SET_DUMP | LIBBIN_OVR_DUMP_FIELDS))) {
2084
+ libbin_ctx_t *pctx = libbin_ctx_from_parent(parent, Qnil, output, 1);
2085
+ if (pctx) {
2086
+ libbin_ctx_sync_from_ruby(pctx);
2087
+ cStructure_dump_fast(self, pctx, output_big, parent, index, flags);
2088
+ libbin_ctx_sync_to_ruby(pctx);
2089
+ return self;
2090
+ }
2091
+ libbin_ctx_t ctx;
2092
+ libbin_ctx_init_dump(&ctx, output);
2093
+ struct top_inst_args args = { self, &ctx, Qnil, output_big, parent, index, flags, 1 };
2094
+ rb_ensure(top_inst_rescue_wrapper, (VALUE)&args, libbin_ctx_ensure, (VALUE)&ctx);
2095
+ return self;
2096
+ }
2097
+ rb_funcall(self, id___set_dump_state, 4, output, output_big, parent, index);
2098
+ rb_ensure(cStructure_dump_body, self, cStructure_dump_ensure, self);
1142
2099
  return self;
1143
2100
  }
1144
2101
 
1145
- /* def __convert(input, output, input_big, output_big, parent = nil, index = nil)
1146
- __set_convert_type(input, output, input_big, output_big, parent, index)
1147
- __convert_fields
1148
- __unset_convert_type
1149
- self
1150
- end */
2102
+ static VALUE cStructure_convert_body(VALUE self) {
2103
+ return rb_funcall(self, id___convert_fields, 0);
2104
+ }
1151
2105
 
1152
- static ID id___convert;
2106
+ static VALUE cStructure_convert_ensure(VALUE self) {
2107
+ return rb_funcall(self, id___unset_convert_state, 0);
2108
+ }
1153
2109
 
1154
- static inline VALUE cDataConverter_convert(int argc, VALUE *argv, VALUE self) {
1155
- VALUE input;
1156
- VALUE output;
1157
- VALUE input_big;
1158
- VALUE output_big;
1159
- VALUE parent;
1160
- VALUE index;
2110
+ static VALUE cStructure_convert(int argc, VALUE *argv, VALUE self) {
2111
+ VALUE input, output, input_big, output_big, parent, index;
1161
2112
  rb_scan_args(argc, argv, "42", &input, &output, &input_big, &output_big, &parent, &index);
1162
- cDataConverter_set_convert_type(self, input, output, input_big, output_big, parent, index);
1163
- rb_funcall(self, id___convert_fields, 0);
1164
- cDataConverter_unset_convert_type(self);
2113
+ uint32_t flags = (CLASS_OF(self) == rb_obj_class(self)) ? libbin_get_structure_flags(rb_obj_class(self)) : ~0u;
2114
+ if (!(flags & (LIBBIN_OVR_SET_CONVERT | LIBBIN_OVR_CONVERT_FIELDS))) {
2115
+ libbin_ctx_t *pctx = libbin_ctx_from_parent(parent, input, output, 2);
2116
+ if (pctx) {
2117
+ libbin_ctx_sync_from_ruby(pctx);
2118
+ cStructure_convert_fast(self, pctx, input_big, output_big, parent, index, flags);
2119
+ libbin_ctx_sync_to_ruby(pctx);
2120
+ return self;
2121
+ }
2122
+ libbin_ctx_t ctx;
2123
+ libbin_ctx_init_convert(&ctx, input, output);
2124
+ struct top_inst_args args = { self, &ctx, input_big, output_big, parent, index, flags, 2 };
2125
+ rb_ensure(top_inst_rescue_wrapper, (VALUE)&args, libbin_ctx_ensure, (VALUE)&ctx);
2126
+ return self;
2127
+ }
2128
+ rb_funcall(self, id___set_convert_state, 6, input, output, input_big, output_big, parent, index);
2129
+ rb_ensure(cStructure_convert_body, self, cStructure_convert_ensure, self);
1165
2130
  return self;
1166
2131
  }
1167
2132
 
1168
- /* def __shape(previous_offset = 0, parent = nil, index = nil, kind = DataShape)
1169
- __set_size_type(previous_offset, parent, index)
1170
- members = __shape_fields(kind)
1171
- __unset_size_type
1172
- return nil if members.values.compact.size <= 0
1173
- kind::new(members)
1174
- end */
2133
+ struct shape_body_args {
2134
+ VALUE self;
2135
+ VALUE kind;
2136
+ long long stride_val;
2137
+ };
1175
2138
 
1176
- static ID id___shape;
2139
+ static VALUE cStructure_shape_body(VALUE args_p) {
2140
+ struct shape_body_args *args = (struct shape_body_args *)args_p;
2141
+ VALUE members = rb_funcall(args->self, id___shape_fields, 1, args->kind);
2142
+ VALUE stride_expr = rb_attr_get(rb_obj_class(args->self), id_stride);
2143
+ if (RTEST(stride_expr))
2144
+ args->stride_val = NUM2LL(cStructure_decode_expression_ctx(args->self, NULL, stride_expr));
2145
+ return members;
2146
+ }
1177
2147
 
1178
- static inline VALUE cDataConverter_shape(int argc, VALUE *argv, VALUE self) {
1179
- VALUE previous_offset;
1180
- VALUE parent;
1181
- VALUE index;
1182
- VALUE kind;
2148
+ static VALUE cStructure_shape_ensure(VALUE self) {
2149
+ return rb_funcall(self, id___unset_size_state, 0);
2150
+ }
2151
+
2152
+ static VALUE cStructure_shape(int argc, VALUE *argv, VALUE self) {
2153
+ VALUE previous_offset, parent, index, kind;
1183
2154
  rb_scan_args(argc, argv, "04", &previous_offset, &parent, &index, &kind);
1184
2155
  if (NIL_P(previous_offset))
1185
2156
  previous_offset = INT2FIX(0);
1186
2157
  if (NIL_P(kind))
1187
2158
  kind = cDataShape;
1188
- cDataConverter_set_size_type(self, previous_offset, parent, index);
1189
- VALUE members = rb_funcall(self, id___shape_fields, 1, kind);
1190
- cDataConverter_unset_size_type(self);
1191
- if (RARRAY_LEN(rb_funcall(rb_funcall(members, rb_intern("values"), 0), rb_intern("compact"), 0)) <= 0)
2159
+ rb_funcall(self, id___set_size_state, 3, previous_offset, parent, index);
2160
+ struct shape_body_args body_args = { self, kind, 0 };
2161
+ VALUE members = rb_ensure(cStructure_shape_body, (VALUE)&body_args, cStructure_shape_ensure, self);
2162
+ long has_members = RARRAY_LEN(rb_funcall(rb_funcall(members, id_values, 0), id_compact, 0)) > 0;
2163
+ if (body_args.stride_val > 0) {
2164
+ ptrdiff_t prev_off = NUM2LL(previous_offset);
2165
+ VALUE target_end = LL2NUM(prev_off + (ptrdiff_t)body_args.stride_val - 1);
2166
+ if (!has_members) {
2167
+ VALUE empty_args[] = { previous_offset, target_end };
2168
+ return rb_class_new_instance(2, empty_args, kind);
2169
+ }
2170
+ VALUE shape = rb_class_new_instance(1, &members, kind);
2171
+ rb_funcall(shape, id___extend_range, 2, previous_offset, target_end);
2172
+ return shape;
2173
+ }
2174
+ if (!has_members)
1192
2175
  return Qnil;
1193
2176
  return rb_class_new_instance(1, &members, kind);
1194
2177
  }
1195
2178
 
1196
- /* def self.load(input, input_big = LibBin::default_big?, parent = nil, index = nil, length = nil)
1197
- if length
1198
- length.times.collect {
1199
- h = self::new
1200
- h.__load(input, input_big, parent, index)
1201
- }
1202
- else
1203
- h = self::new
1204
- h.__load(input, input_big, parent, index)
1205
- end
1206
- end */
2179
+ #define LIBBIN_LEAF_CACHE_MAX 64
1207
2180
 
1208
- static inline VALUE cDataConverter_singl_load(int argc, VALUE *argv, VALUE self) {
1209
- VALUE input;
1210
- VALUE input_big;
1211
- VALUE parent;
1212
- VALUE index;
1213
- VALUE length;
1214
- rb_scan_args(argc, argv, "14", &input, &input_big, &parent, &index, &length);
1215
- if (NIL_P(input_big))
1216
- input_big = rb_funcall(mLibBin, rb_intern("default_big?"), 0);
2181
+ static inline long libbin_extract_leaf_fields(
2182
+ VALUE fields,
2183
+ struct cField_data **fds,
2184
+ VALUE *field_objs,
2185
+ size_t *out_fixed_bytes)
2186
+ {
2187
+ long nf = RARRAY_LEN(fields);
2188
+ if (nf > LIBBIN_LEAF_CACHE_MAX)
2189
+ return -1;
2190
+ size_t total = 0;
2191
+ int fixed = 1;
2192
+ for (long j = 0; j < nf; j++) {
2193
+ VALUE fobj = RARRAY_CONST_PTR(fields)[j];
2194
+ struct cField_data *fd;
2195
+ TypedData_Get_Struct(fobj, struct cField_data, &cField_type, fd);
2196
+ field_objs[j] = fobj;
2197
+ fds[j] = fd;
2198
+ if (fixed) {
2199
+ size_t esz = libbin_scalar_elem_size((libbin_scalar_kind_t)fd->scalar_kind);
2200
+ if (esz == 0) {
2201
+ fixed = 0;
2202
+ } else if (NIL_P(fd->length)) {
2203
+ if (fd->scalar_kind == SCALAR_STR || fd->scalar_kind == SCALAR_ZSTR || fd->scalar_kind == SCALAR_SKIP)
2204
+ fixed = 0;
2205
+ else
2206
+ total += esz;
2207
+ } else if (FIXNUM_P(fd->length) || RB_INTEGER_TYPE_P(fd->length)) {
2208
+ long flen = NUM2LONG(fd->length);
2209
+ if (flen < 0)
2210
+ fixed = 0;
2211
+ else
2212
+ total += esz * (size_t)flen;
2213
+ } else {
2214
+ fixed = 0;
2215
+ }
2216
+ }
2217
+ }
2218
+ *out_fixed_bytes = fixed ? total : 0;
2219
+ return nf;
2220
+ }
2221
+
2222
+ static VALUE cStructure_singl_load_ctx(
2223
+ VALUE klass,
2224
+ libbin_ctx_t *ctx,
2225
+ VALUE input_big,
2226
+ VALUE parent,
2227
+ VALUE index,
2228
+ VALUE length,
2229
+ uint32_t flags)
2230
+ {
2231
+ int fast_alloc = !(flags & LIBBIN_OVR_INIT);
2232
+ int fast_inst = !(flags & (LIBBIN_OVR_INST_LOAD | LIBBIN_OVR_SET_LOAD | LIBBIN_OVR_LOAD_FIELDS));
1217
2233
  VALUE res;
1218
2234
  if (!NIL_P(length)) {
1219
2235
  long l = NUM2LONG(length);
2236
+ if (l < 0)
2237
+ rb_raise(rb_eArgError, "length must be non-negative: %ld", l);
1220
2238
  res = rb_ary_new_capa(l);
1221
- for (long i = 0; i < l; i++) {
1222
- VALUE obj = rb_class_new_instance(0, NULL, self);
1223
- rb_funcall(obj, id___load, 4, input, input_big, parent, index);
1224
- rb_ary_store(res, i, obj);
2239
+ if (fast_alloc && fast_inst && l > 0 &&
2240
+ (flags & LIBBIN_ALL_SCALAR_LEAF) && !(flags & LIBBIN_FAST_LOAD_MASK) &&
2241
+ !LIBBIN_ATOMIC_LOAD(&libbin_scalar_overridden)) {
2242
+ VALUE fields = rb_attr_get(klass, id_fields);
2243
+ struct cField_data *fds[LIBBIN_LEAF_CACHE_MAX];
2244
+ VALUE fobjs[LIBBIN_LEAF_CACHE_MAX];
2245
+ size_t elem_bytes = 0;
2246
+ long nf = libbin_extract_leaf_fields(fields, fds, fobjs, &elem_bytes);
2247
+ if (nf >= 0) {
2248
+ int ibig = RTEST(input_big);
2249
+ size_t depth = libbin_ctx_push_frame(ctx, Qnil, 0, Qnil);
2250
+ for (long i = 0; i < l; i++) {
2251
+ VALUE obj = cStructure_alloc(klass);
2252
+ if (depth < LIBBIN_MAX_FRAMES) {
2253
+ ctx->frames[depth].self = obj;
2254
+ ctx->frames[depth].index = NIL_P(index) ? LONG2NUM(i) : index;
2255
+ }
2256
+ for (long j = 0; j < nf; j++) {
2257
+ if (depth < LIBBIN_MAX_FRAMES)
2258
+ ctx->frames[depth].field = fobjs[j];
2259
+ VALUE val = libbin_scalar_load_fast((libbin_scalar_kind_t)fds[j]->scalar_kind, &ctx->in_io, ibig, fds[j]->length);
2260
+ if (!NIL_P(fds[j]->name))
2261
+ rb_ivar_set(obj, fds[j]->ivar, val);
2262
+ }
2263
+ rb_ary_push(res, obj);
2264
+ }
2265
+ RB_GC_GUARD(fields);
2266
+ libbin_ctx_pop_frame(ctx, depth);
2267
+ return res;
2268
+ }
2269
+ }
2270
+ if (fast_alloc && fast_inst) {
2271
+ for (long i = 0; i < l; i++) {
2272
+ VALUE obj = cStructure_alloc(klass);
2273
+ ctx->pending_index = NIL_P(index) ? LONG2NUM(i) : index;
2274
+ cStructure_load_fast(obj, ctx, input_big, parent, index, flags);
2275
+ rb_ary_push(res, obj);
2276
+ }
2277
+ ctx->pending_index = Qnil;
2278
+ } else if (fast_inst) {
2279
+ for (long i = 0; i < l; i++) {
2280
+ VALUE obj = rb_class_new_instance(0, NULL, klass);
2281
+ ctx->pending_index = NIL_P(index) ? LONG2NUM(i) : index;
2282
+ cStructure_load_fast(obj, ctx, input_big, parent, index, flags);
2283
+ rb_ary_push(res, obj);
2284
+ }
2285
+ ctx->pending_index = Qnil;
2286
+ } else {
2287
+ for (long i = 0; i < l; i++) {
2288
+ VALUE obj = fast_alloc ? cStructure_alloc(klass) : rb_class_new_instance(0, NULL, klass);
2289
+ libbin_ctx_sync_to_ruby(ctx);
2290
+ rb_funcall(obj, id___load, 4, ctx->in_io.io, input_big, parent, index);
2291
+ libbin_ctx_sync_from_ruby(ctx);
2292
+ rb_ary_push(res, obj);
2293
+ }
1225
2294
  }
1226
2295
  return res;
1227
2296
  } else {
1228
- res = rb_class_new_instance(0, NULL, self);
1229
- rb_funcall(res, id___load, 4, input, input_big, parent, index);
2297
+ res = fast_alloc ? cStructure_alloc(klass) : rb_class_new_instance(0, NULL, klass);
2298
+ if (fast_inst) {
2299
+ cStructure_load_fast(res, ctx, input_big, parent, index, flags);
2300
+ } else {
2301
+ libbin_ctx_sync_to_ruby(ctx);
2302
+ rb_funcall(res, id___load, 4, ctx->in_io.io, input_big, parent, index);
2303
+ libbin_ctx_sync_from_ruby(ctx);
2304
+ }
2305
+ return res;
1230
2306
  }
1231
- return res;
1232
2307
  }
1233
2308
 
1234
- /* def self.dump(value, output, output_big = LibBin::default_big?, parent = nil, index = nil, length = nil)
1235
- if length
1236
- length.times.each { |i|
1237
- value[i].__dump(output, output_big, parent, index)
1238
- }
1239
- value
1240
- else
1241
- value.__dump(output, output_big, parent, index)
1242
- end
1243
- end */
1244
-
1245
- static inline VALUE cDataConverter_singl_dump(int argc, VALUE *argv, VALUE self) {
1246
- VALUE value;
1247
- VALUE output;
1248
- VALUE output_big;
1249
- VALUE parent;
1250
- VALUE index;
1251
- VALUE length;
1252
- rb_scan_args(argc, argv, "24", &value, &output, &output_big, &parent, &index, &length);
1253
- if (NIL_P(output_big))
1254
- output_big = rb_funcall(mLibBin, rb_intern("default_big?"), 0);
2309
+ static VALUE cStructure_singl_dump_ctx(
2310
+ VALUE klass,
2311
+ VALUE value,
2312
+ libbin_ctx_t *ctx,
2313
+ VALUE output_big,
2314
+ VALUE parent,
2315
+ VALUE index,
2316
+ VALUE length,
2317
+ uint32_t flags)
2318
+ {
2319
+ (void)klass;
2320
+ int fast_inst = !(flags & (LIBBIN_OVR_INST_DUMP | LIBBIN_OVR_SET_DUMP | LIBBIN_OVR_DUMP_FIELDS));
1255
2321
  if (!NIL_P(length)) {
2322
+ Check_Type(value, T_ARRAY);
1256
2323
  long l = NUM2LONG(length);
1257
- for (long i = 0; i < l; i++)
1258
- rb_funcall(rb_ary_entry(value, i), id___dump, 4, output, output_big, parent, index);
1259
- } else
1260
- rb_funcall(value, id___dump, 4, output, output_big, parent, index);
2324
+ if (l < 0)
2325
+ rb_raise(rb_eArgError, "length must be non-negative: %ld", l);
2326
+ if (RARRAY_LEN(value) < l)
2327
+ rb_raise(rb_eArgError, "array too short for length: got %ld needed %ld", RARRAY_LEN(value), l);
2328
+ if (fast_inst && l > 0 &&
2329
+ (flags & LIBBIN_ALL_SCALAR_LEAF) && !(flags & LIBBIN_FAST_DUMP_MASK) &&
2330
+ !LIBBIN_ATOMIC_LOAD(&libbin_scalar_overridden)) {
2331
+ VALUE fields = rb_attr_get(klass, id_fields);
2332
+ struct cField_data *fds[LIBBIN_LEAF_CACHE_MAX];
2333
+ VALUE fobjs[LIBBIN_LEAF_CACHE_MAX];
2334
+ size_t elem_bytes = 0;
2335
+ long nf = libbin_extract_leaf_fields(fields, fds, fobjs, &elem_bytes);
2336
+ if (nf >= 0) {
2337
+ if (elem_bytes > 0)
2338
+ libbin_io_reserve_output(&ctx->out_io, (size_t)l * elem_bytes);
2339
+ int obig = RTEST(output_big);
2340
+ size_t depth = libbin_ctx_push_frame(ctx, Qnil, 1, Qnil);
2341
+ for (long i = 0; i < l; i++) {
2342
+ VALUE elem = rb_ary_entry(value, i);
2343
+ VALUE fidx = NIL_P(index) ? LONG2NUM(i) : index;
2344
+ if (RB_LIKELY(rb_obj_class(elem) == klass && CLASS_OF(elem) == klass)) {
2345
+ if (depth < LIBBIN_MAX_FRAMES) {
2346
+ ctx->frames[depth].self = elem;
2347
+ ctx->frames[depth].index = fidx;
2348
+ }
2349
+ for (long j = 0; j < nf; j++) {
2350
+ if (depth < LIBBIN_MAX_FRAMES)
2351
+ ctx->frames[depth].field = fobjs[j];
2352
+ VALUE val = NIL_P(fds[j]->name) ? Qnil : rb_ivar_get(elem, fds[j]->ivar);
2353
+ libbin_scalar_dump_fast((libbin_scalar_kind_t)fds[j]->scalar_kind, val, &ctx->out_io, obig, fds[j]->length);
2354
+ }
2355
+ } else {
2356
+ libbin_ctx_sync_to_ruby(ctx);
2357
+ rb_funcall(elem, id___dump, 4, ctx->out_io.io, output_big, parent, index);
2358
+ libbin_ctx_sync_from_ruby(ctx);
2359
+ }
2360
+ }
2361
+ RB_GC_GUARD(fields);
2362
+ libbin_ctx_pop_frame(ctx, depth);
2363
+ return value;
2364
+ }
2365
+ }
2366
+ if (fast_inst) {
2367
+ for (long i = 0; i < l; i++) {
2368
+ VALUE elem = rb_ary_entry(value, i);
2369
+ if (rb_obj_class(elem) == klass) {
2370
+ ctx->pending_index = NIL_P(index) ? LONG2NUM(i) : index;
2371
+ cStructure_dump_fast(elem, ctx, output_big, parent, index, flags);
2372
+ } else {
2373
+ libbin_ctx_sync_to_ruby(ctx);
2374
+ rb_funcall(elem, id___dump, 4, ctx->out_io.io, output_big, parent, index);
2375
+ libbin_ctx_sync_from_ruby(ctx);
2376
+ }
2377
+ }
2378
+ ctx->pending_index = Qnil;
2379
+ } else {
2380
+ for (long i = 0; i < l; i++) {
2381
+ libbin_ctx_sync_to_ruby(ctx);
2382
+ rb_funcall(rb_ary_entry(value, i), id___dump, 4, ctx->out_io.io, output_big, parent, index);
2383
+ libbin_ctx_sync_from_ruby(ctx);
2384
+ }
2385
+ }
2386
+ } else {
2387
+ if (fast_inst && rb_obj_class(value) == klass) {
2388
+ cStructure_dump_fast(value, ctx, output_big, parent, index, flags);
2389
+ } else {
2390
+ libbin_ctx_sync_to_ruby(ctx);
2391
+ rb_funcall(value, id___dump, 4, ctx->out_io.io, output_big, parent, index);
2392
+ libbin_ctx_sync_from_ruby(ctx);
2393
+ }
2394
+ }
1261
2395
  return value;
1262
2396
  }
1263
2397
 
1264
- /* def self.convert(input, output, input_big = LibBin::default_big?, output_big = !input_big, parent = nil, index = nil, length = nil)
1265
- if length
1266
- length.times.collect {
1267
- h = self::new
1268
- h.__convert(input, output, input_big, output_big, parent, index)
2398
+ static VALUE cStructure_singl_convert_ctx(
2399
+ VALUE klass,
2400
+ libbin_ctx_t *ctx,
2401
+ VALUE input_big,
2402
+ VALUE output_big,
2403
+ VALUE parent,
2404
+ VALUE index,
2405
+ VALUE length,
2406
+ uint32_t flags)
2407
+ {
2408
+ int fast_alloc = !(flags & LIBBIN_OVR_INIT);
2409
+ int fast_inst = !(flags & (LIBBIN_OVR_INST_CONVERT | LIBBIN_OVR_SET_CONVERT | LIBBIN_OVR_CONVERT_FIELDS));
2410
+ VALUE res;
2411
+ if (!NIL_P(length)) {
2412
+ long l = NUM2LONG(length);
2413
+ if (l < 0)
2414
+ rb_raise(rb_eArgError, "length must be non-negative: %ld", l);
2415
+ res = rb_ary_new_capa(l);
2416
+ if (fast_alloc && fast_inst && l > 0 &&
2417
+ (flags & LIBBIN_ALL_SCALAR_LEAF) && !(flags & LIBBIN_FAST_CONVERT_MASK) &&
2418
+ !LIBBIN_ATOMIC_LOAD(&libbin_scalar_overridden)) {
2419
+ VALUE fields = rb_attr_get(klass, id_fields);
2420
+ struct cField_data *fds[LIBBIN_LEAF_CACHE_MAX];
2421
+ VALUE fobjs[LIBBIN_LEAF_CACHE_MAX];
2422
+ size_t elem_bytes = 0;
2423
+ long nf = libbin_extract_leaf_fields(fields, fds, fobjs, &elem_bytes);
2424
+ if (nf >= 0) {
2425
+ if (elem_bytes > 0)
2426
+ libbin_io_reserve_output(&ctx->out_io, (size_t)l * elem_bytes);
2427
+ int ibig = RTEST(input_big);
2428
+ int obig = RTEST(output_big);
2429
+ size_t depth = libbin_ctx_push_frame(ctx, Qnil, 2, Qnil);
2430
+ for (long i = 0; i < l; i++) {
2431
+ VALUE obj = cStructure_alloc(klass);
2432
+ if (depth < LIBBIN_MAX_FRAMES) {
2433
+ ctx->frames[depth].self = obj;
2434
+ ctx->frames[depth].index = NIL_P(index) ? LONG2NUM(i) : index;
2435
+ }
2436
+ for (long j = 0; j < nf; j++) {
2437
+ if (depth < LIBBIN_MAX_FRAMES)
2438
+ ctx->frames[depth].field = fobjs[j];
2439
+ VALUE val = libbin_scalar_convert_fast((libbin_scalar_kind_t)fds[j]->scalar_kind, &ctx->in_io, &ctx->out_io, ibig, obig, fds[j]->length);
2440
+ if (!NIL_P(fds[j]->name))
2441
+ rb_ivar_set(obj, fds[j]->ivar, val);
2442
+ }
2443
+ rb_ary_push(res, obj);
1269
2444
  }
1270
- else
1271
- h = self::new
1272
- h.__convert(input, output, input_big, output_big, parent, index)
1273
- end
1274
- end */
1275
-
1276
- static inline VALUE cDataConverter_singl_convert(int argc, VALUE *argv, VALUE self) {
1277
- VALUE input;
1278
- VALUE output;
2445
+ RB_GC_GUARD(fields);
2446
+ libbin_ctx_pop_frame(ctx, depth);
2447
+ return res;
2448
+ }
2449
+ }
2450
+ if (fast_alloc && fast_inst) {
2451
+ for (long i = 0; i < l; i++) {
2452
+ VALUE obj = cStructure_alloc(klass);
2453
+ ctx->pending_index = NIL_P(index) ? LONG2NUM(i) : index;
2454
+ cStructure_convert_fast(obj, ctx, input_big, output_big, parent, index, flags);
2455
+ rb_ary_push(res, obj);
2456
+ }
2457
+ ctx->pending_index = Qnil;
2458
+ } else if (fast_inst) {
2459
+ for (long i = 0; i < l; i++) {
2460
+ VALUE obj = rb_class_new_instance(0, NULL, klass);
2461
+ ctx->pending_index = NIL_P(index) ? LONG2NUM(i) : index;
2462
+ cStructure_convert_fast(obj, ctx, input_big, output_big, parent, index, flags);
2463
+ rb_ary_push(res, obj);
2464
+ }
2465
+ ctx->pending_index = Qnil;
2466
+ } else {
2467
+ for (long i = 0; i < l; i++) {
2468
+ VALUE obj = fast_alloc ? cStructure_alloc(klass) : rb_class_new_instance(0, NULL, klass);
2469
+ libbin_ctx_sync_to_ruby(ctx);
2470
+ rb_funcall(obj, id___convert, 6, ctx->in_io.io, ctx->out_io.io, input_big, output_big, parent, index);
2471
+ libbin_ctx_sync_from_ruby(ctx);
2472
+ rb_ary_push(res, obj);
2473
+ }
2474
+ }
2475
+ return res;
2476
+ } else {
2477
+ res = fast_alloc ? cStructure_alloc(klass) : rb_class_new_instance(0, NULL, klass);
2478
+ if (fast_inst) {
2479
+ cStructure_convert_fast(res, ctx, input_big, output_big, parent, index, flags);
2480
+ } else {
2481
+ libbin_ctx_sync_to_ruby(ctx);
2482
+ rb_funcall(res, id___convert, 6, ctx->in_io.io, ctx->out_io.io, input_big, output_big, parent, index);
2483
+ libbin_ctx_sync_from_ruby(ctx);
2484
+ }
2485
+ return res;
2486
+ }
2487
+ }
2488
+
2489
+ struct top_singl_args {
2490
+ VALUE klass;
2491
+ VALUE value;
2492
+ libbin_ctx_t *ctx;
1279
2493
  VALUE input_big;
1280
2494
  VALUE output_big;
1281
2495
  VALUE parent;
1282
2496
  VALUE index;
1283
2497
  VALUE length;
2498
+ uint32_t flags;
2499
+ uint8_t mode;
2500
+ };
2501
+
2502
+ static VALUE top_singl_body(VALUE args_p) {
2503
+ struct top_singl_args *a = (struct top_singl_args *)args_p;
2504
+ if (a->mode == 0)
2505
+ return cStructure_singl_load_ctx(a->klass, a->ctx, a->input_big, a->parent, a->index, a->length, a->flags);
2506
+ else if (a->mode == 1)
2507
+ return cStructure_singl_dump_ctx(a->klass, a->value, a->ctx, a->output_big, a->parent, a->index, a->length, a->flags);
2508
+ else
2509
+ return cStructure_singl_convert_ctx(a->klass, a->ctx, a->input_big, a->output_big, a->parent, a->index, a->length, a->flags);
2510
+ }
2511
+
2512
+ static VALUE top_singl_rescue_wrapper(VALUE args_p) {
2513
+ struct top_singl_args *a = (struct top_singl_args *)args_p;
2514
+ return rb_rescue(top_singl_body, args_p, libbin_ctx_rescue, (VALUE)a->ctx);
2515
+ }
2516
+
2517
+ static VALUE cStructure_singl_load(int argc, VALUE *argv, VALUE self) {
2518
+ VALUE input, input_big, parent, index, length;
2519
+ rb_scan_args(argc, argv, "14", &input, &input_big, &parent, &index, &length);
2520
+ if (NIL_P(input_big))
2521
+ input_big = rb_funcall(mLibBin, id_default_big_p, 0);
2522
+ uint32_t flags = libbin_get_structure_flags(self);
2523
+ libbin_ctx_t *pctx = libbin_ctx_from_parent(parent, input, Qnil, 0);
2524
+ if (pctx) {
2525
+ libbin_ctx_sync_from_ruby(pctx);
2526
+ VALUE res = cStructure_singl_load_ctx(self, pctx, input_big, parent, index, length, flags);
2527
+ libbin_ctx_sync_to_ruby(pctx);
2528
+ return res;
2529
+ }
2530
+ libbin_ctx_t ctx;
2531
+ libbin_ctx_init_load(&ctx, input);
2532
+ struct top_singl_args args = { self, Qnil, &ctx, input_big, Qnil, parent, index, length, flags, 0 };
2533
+ return rb_ensure(top_singl_rescue_wrapper, (VALUE)&args, libbin_ctx_ensure, (VALUE)&ctx);
2534
+ }
2535
+
2536
+ static VALUE cStructure_singl_dump(int argc, VALUE *argv, VALUE self) {
2537
+ VALUE value, output, output_big, parent, index, length;
2538
+ rb_scan_args(argc, argv, "24", &value, &output, &output_big, &parent, &index, &length);
2539
+ if (NIL_P(output_big))
2540
+ output_big = rb_funcall(mLibBin, id_default_big_p, 0);
2541
+ uint32_t flags = libbin_get_structure_flags(self);
2542
+ libbin_ctx_t *pctx = libbin_ctx_from_parent(parent, Qnil, output, 1);
2543
+ if (pctx) {
2544
+ libbin_ctx_sync_from_ruby(pctx);
2545
+ VALUE res = cStructure_singl_dump_ctx(self, value, pctx, output_big, parent, index, length, flags);
2546
+ libbin_ctx_sync_to_ruby(pctx);
2547
+ return res;
2548
+ }
2549
+ libbin_ctx_t ctx;
2550
+ libbin_ctx_init_dump(&ctx, output);
2551
+ struct top_singl_args args = { self, value, &ctx, Qnil, output_big, parent, index, length, flags, 1 };
2552
+ return rb_ensure(top_singl_rescue_wrapper, (VALUE)&args, libbin_ctx_ensure, (VALUE)&ctx);
2553
+ }
2554
+
2555
+ static VALUE cStructure_singl_convert(int argc, VALUE *argv, VALUE self) {
2556
+ VALUE input, output, input_big, output_big, parent, index, length;
1284
2557
  rb_scan_args(argc, argv, "25", &input, &output, &input_big, &output_big, &parent, &index, &length);
1285
2558
  if (NIL_P(input_big))
1286
- input_big = rb_funcall(mLibBin, rb_intern("default_big?"), 0);
2559
+ input_big = rb_funcall(mLibBin, id_default_big_p, 0);
1287
2560
  if (NIL_P(output_big))
1288
2561
  output_big = RTEST(input_big) ? Qfalse : Qtrue;
1289
- VALUE res;
1290
- if (!NIL_P(length)) {
1291
- long l = NUM2LONG(length);
1292
- res = rb_ary_new_capa(l);
1293
- for (long i = 0; i < l; i++) {
1294
- VALUE obj = rb_class_new_instance(0, NULL, self);
1295
- rb_funcall(obj, id___convert, 6, input, output, input_big, output_big, parent, index);
1296
- rb_ary_store(res, i, obj);
1297
- }
1298
- } else {
1299
- res = rb_class_new_instance(0, NULL, self);
1300
- rb_funcall(res, id___convert, 6, input, output, input_big, output_big, parent, index);
2562
+ uint32_t flags = libbin_get_structure_flags(self);
2563
+ libbin_ctx_t *pctx = libbin_ctx_from_parent(parent, input, output, 2);
2564
+ if (pctx) {
2565
+ libbin_ctx_sync_from_ruby(pctx);
2566
+ VALUE res = cStructure_singl_convert_ctx(self, pctx, input_big, output_big, parent, index, length, flags);
2567
+ libbin_ctx_sync_to_ruby(pctx);
2568
+ return res;
1301
2569
  }
1302
- return res;
2570
+ libbin_ctx_t ctx;
2571
+ libbin_ctx_init_convert(&ctx, input, output);
2572
+ struct top_singl_args args = { self, Qnil, &ctx, input_big, output_big, parent, index, length, flags, 2 };
2573
+ return rb_ensure(top_singl_rescue_wrapper, (VALUE)&args, libbin_ctx_ensure, (VALUE)&ctx);
1303
2574
  }
1304
2575
 
1305
- /* def self.shape(value, previous_offset = 0, parent = nil, index = nil, kind = DataShape, length = nil)
1306
- if length
1307
- kind::new(length.times.collect { |i|
1308
- value[i].__shape(previous_offset, parent, index, kind)
1309
- })
1310
- else
1311
- value.__shape(previous_offset, parent, index, kind)
1312
- end
1313
- end */
1314
-
1315
- static inline VALUE cDataConverter_singl_shape(int argc, VALUE *argv, VALUE self) {
2576
+ static VALUE cStructure_singl_shape(int argc, VALUE *argv, VALUE self) {
2577
+ (void)self;
1316
2578
  VALUE value;
1317
2579
  VALUE previous_offset;
1318
2580
  VALUE parent;
@@ -1326,149 +2588,999 @@ static inline VALUE cDataConverter_singl_shape(int argc, VALUE *argv, VALUE self
1326
2588
  kind = cDataShape;
1327
2589
  VALUE res;
1328
2590
  if (!NIL_P(length)) {
2591
+ Check_Type(value, T_ARRAY);
1329
2592
  long l = NUM2LONG(length);
2593
+ if (l < 0)
2594
+ rb_raise(rb_eArgError, "length must be non-negative: %ld", l);
2595
+ if (RARRAY_LEN(value) < l)
2596
+ rb_raise(rb_eArgError, "array too short for length: got %ld needed %ld", RARRAY_LEN(value), l);
2597
+ VALUE cur_offset = previous_offset;
1330
2598
  res = rb_ary_new_capa(l);
1331
- for (long i = 0; i < l; i++)
1332
- rb_ary_store(res, i, rb_funcall(rb_ary_entry(value, i), id___shape, 4, previous_offset, parent, index, kind));
2599
+ for (long i = 0; i < l; i++) {
2600
+ VALUE sh = rb_funcall(rb_ary_entry(value, i), id___shape, 4, cur_offset, parent, index, kind);
2601
+ rb_ary_store(res, i, sh);
2602
+ if (!NIL_P(sh)) {
2603
+ VALUE last = rb_funcall(sh, id_last, 0);
2604
+ if (RTEST(last)) {
2605
+ ptrdiff_t pos = NUM2LL(last);
2606
+ if (pos >= 0)
2607
+ cur_offset = LL2NUM(pos + 1);
2608
+ }
2609
+ }
2610
+ }
1333
2611
  res = rb_class_new_instance(1, &res, kind);
1334
2612
  } else
1335
2613
  res = rb_funcall(value, id___shape, 4, previous_offset, parent, index, kind);
1336
2614
  return res;
1337
2615
  }
1338
2616
 
1339
- static void define_cDataConverter() {
1340
- id_tell = rb_intern("tell");
1341
- id_seek = rb_intern("seek");
2617
+ static void define_cStructure(void) {
1342
2618
  id_fields = rb_intern("@fields");
1343
2619
  id_instance_exec = rb_intern("instance_exec");
1344
-
2620
+ id_last = rb_intern("last");
2621
+ id_values = rb_intern("values");
2622
+ id_compact = rb_intern("compact");
2623
+ id_output = rb_intern("output");
2624
+ id_print = rb_intern("print");
2625
+ id_unpack = rb_intern("unpack");
2626
+ id_pack = rb_intern("pack");
2627
+ id_first = rb_intern("first");
2628
+ id_initialize = rb_intern("initialize");
2629
+ id_instance_method = rb_intern("instance_method");
2630
+ id_method = rb_intern("method");
2631
+ id_owner = rb_intern("owner");
2632
+ id_source_location = rb_intern("source_location");
2633
+ id___libbin_flags = rb_intern("@__libbin_flags");
2634
+ id___libbin_flags_gen = rb_intern("@__libbin_flags_gen");
2635
+ id_stride = rb_intern("@stride");
2636
+ id___extend_range = rb_intern("__extend_range");
2637
+
2638
+ id___set_load_state = rb_intern("__set_load_state");
2639
+ id___unset_load_state = rb_intern("__unset_load_state");
2640
+ id___load_field = rb_intern("__load_field");
1345
2641
  id___load_fields = rb_intern("__load_fields");
1346
2642
  id_load = rb_intern("load");
1347
2643
  id___load = rb_intern("__load");
1348
2644
 
2645
+ id___set_dump_state = rb_intern("__set_dump_state");
2646
+ id___unset_dump_state = rb_intern("__unset_dump_state");
2647
+ id___dump_field = rb_intern("__dump_field");
1349
2648
  id___dump_fields = rb_intern("__dump_fields");
1350
2649
  id_dump = rb_intern("dump");
1351
2650
  id___dump = rb_intern("__dump");
1352
2651
 
2652
+ id___set_convert_state = rb_intern("__set_convert_state");
2653
+ id___unset_convert_state = rb_intern("__unset_convert_state");
2654
+ id___convert_field = rb_intern("__convert_field");
1353
2655
  id___convert_fields = rb_intern("__convert_fields");
1354
2656
  id_convert = rb_intern("convert");
1355
2657
  id___convert = rb_intern("__convert");
1356
2658
 
2659
+ id___set_size_state = rb_intern("__set_size_state");
2660
+ id___unset_size_state = rb_intern("__unset_size_state");
2661
+ id___shape_field = rb_intern("__shape_field");
1357
2662
  id___shape_fields = rb_intern("__shape_fields");
1358
2663
  id_shape = rb_intern("shape");
1359
2664
  id___shape = rb_intern("__shape");
1360
2665
 
1361
- cDataConverter = rb_define_class_under(mLibBin, "DataConverter", rb_cObject);
1362
- rb_define_alloc_func(cDataConverter, cDataConverter_alloc);
1363
- rb_define_method(cDataConverter, "initialize", cDataConverter_initialize, 0);
1364
- rb_define_method(cDataConverter, "__parent", cDataConverter_parent, 0);
1365
- rb_define_method(cDataConverter, "__index", cDataConverter_index, 0);
1366
- rb_define_method(cDataConverter, "__iterator", cDataConverter_iterator, 0);
1367
- rb_define_method(cDataConverter, "__position", cDataConverter_position, 0);
1368
- rb_define_method(cDataConverter, "__input", cDataConverter_input, 0);
1369
- rb_define_method(cDataConverter, "__output", cDataConverter_output, 0);
1370
- rb_define_method(cDataConverter, "__input_big", cDataConverter_input_big, 0);
1371
- rb_define_method(cDataConverter, "__output_big", cDataConverter_output_big, 0);
1372
-
1373
- rb_define_method(cDataConverter, "__set_convert_type", cDataConverter_set_convert_type, 6);
1374
- rb_define_method(cDataConverter, "__unset_convert_type", cDataConverter_unset_convert_type, 0);
1375
- rb_define_method(cDataConverter, "__set_size_type", cDataConverter_set_size_type, 3);
1376
- rb_define_method(cDataConverter, "__unset_size_type", cDataConverter_unset_size_type, 0);
1377
- rb_define_method(cDataConverter, "__set_load_type", cDataConverter_set_load_type, 4);
1378
- rb_define_method(cDataConverter, "__unset_load_type", cDataConverter_unset_load_type, 0);
1379
- rb_define_method(cDataConverter, "__set_dump_type", cDataConverter_set_dump_type, 4);
1380
- rb_define_method(cDataConverter, "__unset_dump_type", cDataConverter_unset_dump_type, 0);
1381
-
1382
- rb_define_method(cDataConverter, "__decode_expression", cDataConverter_decode_expression, 1);
1383
- rb_define_method(cDataConverter, "__decode_seek_offset", cDataConverter_decode_seek_offset, 2);
1384
- rb_define_method(cDataConverter, "__decode_condition", cDataConverter_decode_condition, 1);
1385
- rb_define_method(cDataConverter, "__decode_count", cDataConverter_decode_count, 1);
1386
- rb_define_method(cDataConverter, "__decode_type", cDataConverter_decode_type, 1);
1387
- rb_define_method(cDataConverter, "__decode_length", cDataConverter_decode_length, 1);
1388
- rb_define_method(cDataConverter, "__decode_static_conditions", cDataConverter_decode_static_conditions, 1);
1389
- rb_define_method(cDataConverter, "__decode_dynamic_conditions", cDataConverter_decode_dynamic_conditions, 1);
1390
-
1391
- rb_define_method(cDataConverter, "__restore_context", cDataConverter_restore_context, 0);
1392
-
1393
- rb_define_method(cDataConverter, "__convert_field", cDataConverter_convert_field, 1);
1394
- rb_define_method(cDataConverter, "__load_field", cDataConverter_load_field, 1);
1395
- rb_define_method(cDataConverter, "__dump_field", cDataConverter_dump_field, 2);
1396
- rb_define_method(cDataConverter, "__shape_field", cDataConverter_shape_field, 3);
1397
-
1398
- rb_define_method(cDataConverter, "__load_fields", cDataConverter_load_fields, 0);
1399
- rb_define_method(cDataConverter, "__dump_fields", cDataConverter_dump_fields, 0);
1400
- rb_define_method(cDataConverter, "__convert_fields", cDataConverter_convert_fields, 0);
1401
- rb_define_method(cDataConverter, "__shape_fields", cDataConverter_shape_fields, 1);
1402
-
1403
- rb_define_method(cDataConverter, "__load", cDataConverter_load, -1);
1404
- rb_define_method(cDataConverter, "__dump", cDataConverter_dump, -1);
1405
- rb_define_method(cDataConverter, "__convert", cDataConverter_convert, -1);
1406
- rb_define_method(cDataConverter, "__shape", cDataConverter_shape, -1);
1407
-
1408
- rb_define_singleton_method(cDataConverter, "load", cDataConverter_singl_load, -1);
1409
- rb_define_singleton_method(cDataConverter, "dump", cDataConverter_singl_dump, -1);
1410
- rb_define_singleton_method(cDataConverter, "convert", cDataConverter_singl_convert, -1);
1411
- rb_define_singleton_method(cDataConverter, "shape", cDataConverter_singl_shape, -1);
2666
+ cStructure = rb_define_class_under(mLibBin, "Structure", rb_cObject);
2667
+ cStructure_sclass = rb_singleton_class(cStructure);
2668
+ rb_gc_register_mark_object(cStructure_sclass);
2669
+ #ifdef HAVE_RB_RACTOR_LOCAL_STORAGE_VALUE_NEWKEY
2670
+ libbin_ractor_flags_key = rb_ractor_local_storage_value_newkey();
2671
+ #endif
2672
+ rb_define_alloc_func(cStructure, cStructure_alloc);
2673
+ rb_define_singleton_method(cStructure, "method_added", cStructure_method_added, 1);
2674
+ rb_define_singleton_method(cStructure, "singleton_method_added", cStructure_singleton_method_added, 1);
2675
+ rb_define_singleton_method(cStructure, "__bump_override_gen", cStructure_bump_override_gen, 0);
2676
+ rb_define_singleton_method(cStructure, "__set_data_types_file", cStructure_set_data_types_file, 1);
2677
+ rb_define_singleton_method(cStructure, "__preprocess_expression", cStructure_preprocess_expression, 1);
2678
+ /**
2679
+ * Create new Structure object.
2680
+ * @return [Structure] a new Structure instance with state set to nil.
2681
+ */
2682
+ rb_define_method(cStructure, "initialize", cStructure_initialize, 0);
2683
+
2684
+ DEFINE_STRUCT_STATE_ACCESSORS(parent);
2685
+ DEFINE_STRUCT_STATE_ACCESSORS(index);
2686
+ DEFINE_STRUCT_STATE_ACCESSORS(position);
2687
+ DEFINE_STRUCT_STATE_ACCESSORS(cur_position);
2688
+ DEFINE_STRUCT_STATE_ACCESSORS(input);
2689
+ DEFINE_STRUCT_STATE_ACCESSORS(output);
2690
+ DEFINE_STRUCT_STATE_ACCESSORS(input_big);
2691
+ DEFINE_STRUCT_STATE_ACCESSORS(output_big);
2692
+
2693
+ DEFINE_STRUCT_STATE_ACCESSORS(offset);
2694
+ DEFINE_STRUCT_STATE_ACCESSORS(condition);
2695
+ DEFINE_STRUCT_STATE_ACCESSORS(type);
2696
+ DEFINE_STRUCT_STATE_ACCESSORS(length);
2697
+ DEFINE_STRUCT_STATE_ACCESSORS(iterator);
2698
+ DEFINE_STRUCT_STATE_ACCESSORS(count);
2699
+ DEFINE_STRUCT_STATE_ACCESSORS(value);
2700
+
2701
+ /**
2702
+ * @overload __set_convert_state(input, output, input_big, output_big, parent, index)
2703
+ * Set attributes for conversion
2704
+ * @param input [IO] the stream to read data from
2705
+ * @param output [IO] the stream to write data to
2706
+ * @param input_big [Boolean] str endianness of +input+
2707
+ * @param output_big [Boolean] str endianness of +output+
2708
+ * @param parent [nil,Structure] the parent if it exists, nil otherwise
2709
+ * @param index [nil,Integer] the index if the structure is repeated, nil otherwise
2710
+ * @return [nil]
2711
+ * @example
2712
+ * # Orignal Ruby implementation
2713
+ * def __set_convert_state(input, output, input_big, output_big, parent, index)
2714
+ * __input_big = input_big
2715
+ * __output_big = output_big
2716
+ * __input = input
2717
+ * __output = output
2718
+ * __parent = parent
2719
+ * __index = index
2720
+ * __position = input.tell
2721
+ * __cur_position = __position
2722
+ * end
2723
+ */
2724
+ rb_define_method(cStructure, "__set_convert_state", cStructure_set_convert_state, 6);
2725
+ /**
2726
+ * Unset attributes after conversion.
2727
+ * @return [nil]
2728
+ * @example
2729
+ * # Orignal Ruby implementation
2730
+ * def __unset_convert_state
2731
+ * __input_big = nil
2732
+ * __output_big = nil
2733
+ * __input = nil
2734
+ * __output = nil
2735
+ * __parent = nil
2736
+ * __index = nil
2737
+ * __position = nil
2738
+ * __cur_position = nil
2739
+ * end
2740
+ */
2741
+ rb_define_method(cStructure, "__unset_convert_state", cStructure_unset_convert_state, 0);
2742
+ /**
2743
+ * @overload __set_size_state(position, parent, index)
2744
+ * Set attributes for computing size or shape
2745
+ * @param position [Integer] The position of the field
2746
+ * @param parent [nil,Structure] the parent if it exists, nil otherwise
2747
+ * @param index [nil,Integer] the index if the structure is repeated, nil otherwise
2748
+ * @return [nil]
2749
+ * @example
2750
+ * # Orignal Ruby implementation
2751
+ * def __set_size_state(position, parent, index)
2752
+ * __parent = parent
2753
+ * __index = index
2754
+ * __position = position
2755
+ * __cur_position = __position
2756
+ * end
2757
+ */
2758
+ rb_define_method(cStructure, "__set_size_state", cStructure_set_size_state, 3);
2759
+ /**
2760
+ * Unset attributes after size or shape computation
2761
+ * @return [nil]
2762
+ * @example
2763
+ * # Orignal Ruby implementation
2764
+ * def __unset_size_state
2765
+ * __parent = nil
2766
+ * __index = nil
2767
+ * __position = nil
2768
+ * __cur_position = nil
2769
+ * end
2770
+ */
2771
+ rb_define_method(cStructure, "__unset_size_state", cStructure_unset_size_state, 0);
2772
+ /**
2773
+ * @overload __set_load_state(input, input_big, parent, index)
2774
+ * Set attributes for loading
2775
+ * @param input [IO] the stream to read data from
2776
+ * @param input_big [Boolean] str endianness of +input+
2777
+ * @param parent [nil,Structure] the parent if it exists, nil otherwise
2778
+ * @param index [nil,Integer] the index if the structure is repeated, nil otherwise
2779
+ * @return [nil]
2780
+ * @example
2781
+ * # Orignal Ruby implementation
2782
+ * def __set_load_state(input, input_big, parent, index)
2783
+ * __input_big = input_big
2784
+ * __input = input
2785
+ * __parent = parent
2786
+ * __index = index
2787
+ * __position = input.tell
2788
+ * __cur_position = __position
2789
+ * end
2790
+ */
2791
+ rb_define_method(cStructure, "__set_load_state", cStructure_set_load_state, 4);
2792
+ /**
2793
+ * Unset attributes after loading
2794
+ * @return [nil]
2795
+ * @example
2796
+ * # Orignal Ruby implementation
2797
+ * def __unset_load_state
2798
+ * __input_big = nil
2799
+ * __input = nil
2800
+ * __parent = nil
2801
+ * __index = nil
2802
+ * __position = nil
2803
+ * __cur_position = nil
2804
+ * end
2805
+ */
2806
+ rb_define_method(cStructure, "__unset_load_state", cStructure_unset_load_state, 0);
2807
+ /**
2808
+ * @overload __set_dump_state(output, output_big, parent, index)
2809
+ * Set attributes for dumping
2810
+ * @param output [IO] the stream to write data to
2811
+ * @param output_big [Boolean] str endianness of +output+
2812
+ * @param parent [nil,Structure] the parent if it exists, nil otherwise
2813
+ * @param index [nil,Integer] the index if the structure is repeated, nil otherwise
2814
+ * @return [nil]
2815
+ * @example
2816
+ * # Orignal Ruby implementation
2817
+ * def __set_dump_state(output, output_big, parent, index)
2818
+ * __output_big = output_big
2819
+ * __output = output
2820
+ * __parent = parent
2821
+ * __index = index
2822
+ * __position = output.tell
2823
+ * __cur_position = __position
2824
+ * end
2825
+ */
2826
+ rb_define_method(cStructure, "__set_dump_state", cStructure_set_dump_state, 4);
2827
+ /**
2828
+ * Unset attributes after dumping
2829
+ * @return [nil]
2830
+ * @example
2831
+ * # Orignal Ruby implementation
2832
+ * def __unset_dump_state
2833
+ * __output_big = nil
2834
+ * __output = nil
2835
+ * __parent = nil
2836
+ * __index = nil
2837
+ * __position = nil
2838
+ * __cur_position = nil
2839
+ * end
2840
+ */
2841
+ rb_define_method(cStructure, "__unset_dump_state", cStructure_unset_dump_state, 0);
2842
+
2843
+ /**
2844
+ * @overload __decode_expression(expression)
2845
+ * Decode the given expression in the context of the receiver.
2846
+ * @param expression [Proc,Object] the expression to decode
2847
+ * @return [Object] the decoded value
2848
+ * @note Do not overload, this is not called through the usual ruby dispatch for performance reasons
2849
+ * @example
2850
+ * # Original Ruby implementation
2851
+ * def __decode_expression(expression)
2852
+ * if expression.is_a?(Proc)
2853
+ * instance_exec &expression
2854
+ * else
2855
+ * expression
2856
+ * end
2857
+ * end
2858
+ */
2859
+ rb_define_method(cStructure, "__decode_expression", cStructure_decode_expression, 1);
2860
+ /**
2861
+ * @overload __decode_expect(expect, value)
2862
+ * Decode the given expect expression, given the field value.
2863
+ * @param expect [Proc,Object,nil] the expression to decode
2864
+ * @param value [Object] the field value to validate
2865
+ * @return [Object] returns +value+ if validated. If expect is a Proc, the proc will be passed +value+
2866
+ * as an argument and be evaluated. If expect is a scalar, +expect+ and +value+ will be tested for equality.
2867
+ * If the result of the evaluation or the test is truthy, value is validate. Else an exception is raised.
2868
+ * @example
2869
+ * # Original Ruby implementation
2870
+ * def __decode_expect(expect, value)
2871
+ * return value if expect.nil?
2872
+ * if expect.is_a?(Proc)
2873
+ * raise "could not validate field value: #{value}" unless instance_exec(value, &expect)
2874
+ * else
2875
+ * raise "could not validate field value: #{value} expected: #{expect}" unless expect == value
2876
+ * end
2877
+ * return value
2878
+ * end
2879
+ */
2880
+ rb_define_method(cStructure, "__decode_expect", cStructure_decode_expect, 2);
2881
+ /**
2882
+ * @overload __decode_seek_offset(offset, relative_offset, align, null_offset)
2883
+ * Decode the offset and seek to this position in the active streams.
2884
+ * @param offset [Proc,Integer,nil] the expression to decode
2885
+ * @param relative_offset [Boolean] the offset should be relative to the structure base (+__position+)
2886
+ * @param align [false,Integer] the required alignement of the field
2887
+ * @param null_offset [nil,false,Integer] sentinel offset value treated as absent
2888
+ * @return [nil,false,Integer] return nil if no offset was specified, an Integer if the active streams
2889
+ * had to seek, or false if a null offset was computed.
2890
+ * @note Do not overload, this is not called through the usual ruby dispatch for performance reasons
2891
+ * @example
2892
+ * # Original Ruby implementation
2893
+ * def __decode_seek_offset(offset, relative_offset, align, null_offset)
2894
+ * cur_pos = nil
2895
+ * if !offset
2896
+ * return nil unless align
2897
+ * cur_pos =
2898
+ * if __input
2899
+ * __input.tell
2900
+ * elsif __output
2901
+ * __output.tell
2902
+ * else
2903
+ * __cur_position
2904
+ * end
2905
+ * pad = cur_pos % align
2906
+ * return nil if pad == 0
2907
+ * cur_pos += align - pad
2908
+ * else
2909
+ * cur_pos = __decode_expression(offset)
2910
+ * return false if cur_pos.nil? || cur_pos == false
2911
+ * return false if null_offset && cur_pos == null_offset
2912
+ * cur_pos += __position if relative_offset
2913
+ * cur_pos += align - (cur_pos % align) if align && cur_pos % align > 0
2914
+ * end
2915
+ * __cur_position = cur_pos
2916
+ * __input.seek(cur_pos) if __input
2917
+ * __output.seek(cur_pos) if __output
2918
+ * cur_pos
2919
+ * end
2920
+ */
2921
+ rb_define_method(cStructure, "__decode_seek_offset", cStructure_decode_seek_offset, 4);
2922
+ /**
2923
+ * @overload __decode_condition(condition)
2924
+ * Decode the condition expression
2925
+ * @param condition [Proc,Boolean,nil] the expression to decode
2926
+ * @return [Boolean] the field is active
2927
+ * @note Do not overload, this is not called through the usual ruby dispatch for performance reasons
2928
+ * @example
2929
+ * # Original Ruby implementation
2930
+ * def __decode_condition(condition)
2931
+ * return true unless condition
2932
+ * __decode_expression(condition)
2933
+ * end
2934
+ */
2935
+ rb_define_method(cStructure, "__decode_condition", cStructure_decode_condition, 1);
2936
+ /**
2937
+ * @overload __decode_count(count)
2938
+ * Decode the count expression.
2939
+ * @param count [Proc,Integer,nil] the expression to decode
2940
+ * @return [Integer] 1 if +count+ is nil, the decoded count otherwise
2941
+ * @note Do not overload, this is not called through the usual ruby dispatch for performance reasons
2942
+ * @example
2943
+ * # Original Ruby implementation
2944
+ * def __decode_count(count)
2945
+ * return 1 unless count
2946
+ * __decode_expression(count)
2947
+ * end
2948
+ */
2949
+ rb_define_method(cStructure, "__decode_count", cStructure_decode_count, 1);
2950
+ /**
2951
+ * @overload __decode_type(type)
2952
+ * Decode the type expression.
2953
+ * @param type [Proc,Class] the expression to decode
2954
+ * @return [Class] the decoded type
2955
+ * @note Do not overload, this is not called through the usual ruby dispatch for performance reasons
2956
+ * @example
2957
+ * # Original Ruby implementation
2958
+ * def __decode_type(type)
2959
+ * __decode_expression(type)
2960
+ * end
2961
+ */
2962
+ rb_define_method(cStructure, "__decode_type", cStructure_decode_type, 1);
2963
+ /**
2964
+ * @overload __decode_length(length)
2965
+ * Decode the length expression.
2966
+ * @param length [Proc,Integer,nil] the expression to decode
2967
+ * @return [Integer,nil] nil if the field is not a vector, or the
2968
+ * length of the vector
2969
+ * @note Do not overload, this is not called through the usual ruby dispatch for performance reasons
2970
+ * @example
2971
+ * # Original Ruby implementation
2972
+ * def __decode_length(length)
2973
+ * __decode_expression(length)
2974
+ * end
2975
+ */
2976
+ rb_define_method(cStructure, "__decode_length", cStructure_decode_length, 1);
2977
+ /**
2978
+ * @overload __decode_static_conditions(field)
2979
+ * Sets field specific context. Return nil if the field is inactive.
2980
+ * If the field is a sequence, only +__count+ is set, if not,
2981
+ * +__offset+, +__condition+, +__type+, and +__count+ are
2982
+ * also set.
2983
+ * @param field [Field] the field descriptor
2984
+ * @return [Integer,nil] nil if the field is inactive, the repetition count otherwise
2985
+ * @note Do not overload, this is not called through the usual ruby dispatch for performance reasons
2986
+ * @example
2987
+ * # Original Ruby implementation
2988
+ * def __decode_static_conditions(field)
2989
+ * __offset = nil
2990
+ * __condition = nil
2991
+ * __type = nil
2992
+ * __length = nil
2993
+ * __count = nil
2994
+ * unless field.sequence?
2995
+ * __condition = __decode_condition(field.condition)
2996
+ * return nil unless __condition
2997
+ * __offset = __decode_seek_offset(field.offset, field.relative_offset?, field.align)
2998
+ * return nil if __offset == false
2999
+ * __type = __decode_type(field.type)
3000
+ * __length = __decode_length(field.length)
3001
+ * end
3002
+ * __count = __decode_count(field.count)
3003
+ * end
3004
+ */
3005
+ rb_define_method(cStructure, "__decode_static_conditions", cStructure_decode_static_conditions, 1);
3006
+ /**
3007
+ * @overload __decode_dynamic_conditions(field)
3008
+ * Sets field repetition specific context.
3009
+ * Namely +__offset+, +__condition+, +__type+, and +__length+
3010
+ * should be set if the field repetition is active.
3011
+ * @param field [Field] the field descriptor
3012
+ * @return [Boolean] field repetition is active
3013
+ * @note Do not overload, this is not called through the usual ruby dispatch for performance reasons.
3014
+ * @example
3015
+ * # Original Ruby implementation
3016
+ * def __decode_dynamic_conditions(field)
3017
+ * return true unless field.sequence?
3018
+ * __offset = nil
3019
+ * __condition = nil
3020
+ * __type = nil
3021
+ * __length = nil
3022
+ * __condition = __decode_condition(field.condition)
3023
+ * return false unless __condition
3024
+ * __offset = __decode_seek_offset(field.offset, field.relative_offset?, field.align)
3025
+ * return false if __offset == false
3026
+ * __type = __decode_type(field.type)
3027
+ * __length = __decode_length(field.length)
3028
+ * return true
3029
+ * end
3030
+ */
3031
+ rb_define_method(cStructure, "__decode_dynamic_conditions", cStructure_decode_dynamic_conditions, 1);
3032
+
3033
+ /**
3034
+ * Restore the field specific context.
3035
+ * @return nil
3036
+ * @example
3037
+ * # Original Ruby implementation
3038
+ * def __restore_context
3039
+ * __iterator = nil
3040
+ * __type = nil
3041
+ * __length = nil
3042
+ * __count = nil
3043
+ * __offset = nil
3044
+ * __condition = nil
3045
+ * __value = nil
3046
+ * end
3047
+ */
3048
+ rb_define_method(cStructure, "__restore_context", cStructure_restore_context, 0);
3049
+
3050
+ /**
3051
+ * @overload __convert_field(field)
3052
+ * Load and dump the value of a structure field.
3053
+ * @param field [Field] the field descriptor
3054
+ * @return the field value or nil if the field was inactive
3055
+ * @example
3056
+ * # Original Ruby implementation
3057
+ * def __convert_field(field)
3058
+ * return nil if __decode_static_conditions(field).nil?
3059
+ * vs = __count.times.collect do |it|
3060
+ * __iterator = it
3061
+ * if __decode_dynamic_conditions(field)
3062
+ * __value = __type::convert(__input, __output, __input_big, __output_big, self, it, __length)
3063
+ * __decode_expect(field.expect, __value)
3064
+ * else
3065
+ * nil
3066
+ * end
3067
+ * end
3068
+ * __restore_context
3069
+ * vs = vs.first unless field.count
3070
+ * vs
3071
+ * end
3072
+ */
3073
+ rb_define_method(cStructure, "__convert_field", cStructure_convert_field, 1);
3074
+ /**
3075
+ * @overload __load_field(field)
3076
+ * Load the value of a structure field.
3077
+ * @param field [Field] the field descriptor
3078
+ * @return the field value or nil if the field was inactive
3079
+ * @example
3080
+ * # Original Ruby implementation
3081
+ * def __load_field(field)
3082
+ * return nil if __decode_static_conditions(field).nil?
3083
+ * vs = __count.times.collect do |it|
3084
+ * __iterator = it
3085
+ * if __decode_dynamic_conditions(field)
3086
+ * __value = __type::load(__input, __input_big, self, it, __length)
3087
+ * __decode_expect(field.expect, __value)
3088
+ * else
3089
+ * nil
3090
+ * end
3091
+ * end
3092
+ * __restore_context
3093
+ * vs = vs.first unless field.count
3094
+ * vs
3095
+ * end
3096
+ */
3097
+ rb_define_method(cStructure, "__load_field", cStructure_load_field, 1);
3098
+ /**
3099
+ * @overload __dump_field(value, field)
3100
+ * Dump the value of a structure field.
3101
+ * @param value the field value
3102
+ * @param field [Field] the field descriptor
3103
+ * @return nil
3104
+ * @example
3105
+ * # Original Ruby implementation
3106
+ * def __dump_field(vs, field)
3107
+ * return nil if __decode_static_conditions(field).nil?
3108
+ * vs = [vs] unless field.count
3109
+ * __count.times do |it|
3110
+ * __iterator = it
3111
+ * if __decode_dynamic_conditions(field)
3112
+ * __value = vs[it]
3113
+ * __decode_expect(field.expect, __value)
3114
+ * __type::dump(__value, __output, __output_big, self, it, __length)
3115
+ * end
3116
+ * end
3117
+ * __restore_context
3118
+ * end
3119
+ */
3120
+ rb_define_method(cStructure, "__dump_field", cStructure_dump_field, 2);
3121
+ /**
3122
+ * @overload __shape_field(value, kind, field)
3123
+ * Return the shape of the structure field.
3124
+ * @param value the field value
3125
+ * @param kind [Class] the class of the shape required
3126
+ * @param field [Field] the field descriptor
3127
+ * @return [nil,kind,Array<kind>] the field shape, or nil if the field was inactive
3128
+ * @example
3129
+ * # Original Ruby implementation
3130
+ * def __shape_field(vs, kind, field)
3131
+ * return nil if __decode_static_conditions(field).nil?
3132
+ * vs = [vs] unless field.count
3133
+ * vs = vs.each_with_index.collect do |v, it|
3134
+ * __iterator = it
3135
+ * if __decode_dynamic_conditions(field)
3136
+ * sh = __type::shape(v, __cur_position, self, it, kind, __length)
3137
+ * __cur_position = sh.last + 1 if sh.last && sh.last >= 0
3138
+ * sh
3139
+ * end
3140
+ * end
3141
+ * __restore_context
3142
+ * vs = field.count ? kind.new(vs) : vs.first
3143
+ * vs
3144
+ * end
3145
+ */
3146
+ rb_define_method(cStructure, "__shape_field", cStructure_shape_field, 3);
3147
+
3148
+ /**
3149
+ * Load the fields of the structure. The load state must
3150
+ * have been set beforehand.
3151
+ * @return [Structure] self
3152
+ * @example
3153
+ * # Original Ruby implementation
3154
+ * def __load_fields
3155
+ * field = nil
3156
+ * begin
3157
+ * __fields.each { |field|
3158
+ * send("#{field.name}=", __load_field(field))
3159
+ * }
3160
+ * rescue
3161
+ * STDERR.puts "#{self.class}: #{field.name}(#{field.type})"
3162
+ * raise
3163
+ * end
3164
+ * self
3165
+ * end
3166
+ */
3167
+ rb_define_method(cStructure, "__load_fields", cStructure_load_fields, 0);
3168
+ /**
3169
+ * Dump the fields of the structure. The dump state must
3170
+ * have been set beforehand.
3171
+ * @return [Structure] self
3172
+ * @example
3173
+ * # Original Ruby implementation
3174
+ * def __dump_fields
3175
+ * field = nil
3176
+ * begin
3177
+ * __fields.each { |field|
3178
+ * __dump_field(send(field.name), field)
3179
+ * }
3180
+ * rescue
3181
+ * STDERR.puts "#{self.class}: #{field.name}(#{field.type})"
3182
+ * raise
3183
+ * end
3184
+ * self
3185
+ * end
3186
+ */
3187
+ rb_define_method(cStructure, "__dump_fields", cStructure_dump_fields, 0);
3188
+ /**
3189
+ * Convert the fields of the structure. The conversion
3190
+ * state must have been set beforehand.
3191
+ * @return [Structure] self
3192
+ * @example
3193
+ * # Original Ruby implementation
3194
+ * def __convert_fields
3195
+ * field = nil
3196
+ * begin
3197
+ * __fields.each { |field|
3198
+ * send("#{field.name}=", __convert_field(field))
3199
+ * }
3200
+ * rescue
3201
+ * STDERR.puts "#{self.class}: #{field.name}(#{field.type})"
3202
+ * raise
3203
+ * end
3204
+ * self
3205
+ * end
3206
+ */
3207
+ rb_define_method(cStructure, "__convert_fields", cStructure_convert_fields, 0);
3208
+ /**
3209
+ * @overload __shape_fields(kind)
3210
+ * Return the shape of the structure fields in a Hash, indexed by the fields' names.
3211
+ * The size state must have been set beforehand.
3212
+ * @param kind [Class] the kind of structure to create
3213
+ * @return [Hash{Symbol=>kind}] the fields shape
3214
+ * @example
3215
+ * # Original Ruby implementation
3216
+ * def __shape_fields(kind)
3217
+ * members = {}
3218
+ * field = nil
3219
+ * begin
3220
+ * __fields.each { |field|
3221
+ * members[field.name] = __shape_field(send(field.name), kind, field)
3222
+ * }
3223
+ * rescue
3224
+ * LibBin.output.puts "#{self.class}: #{field.name}(#{field.type})" if LibBin.output
3225
+ * raise
3226
+ * end
3227
+ * return members
3228
+ * end
3229
+ */
3230
+ rb_define_method(cStructure, "__shape_fields", cStructure_shape_fields, 1);
3231
+
3232
+ /**
3233
+ * @overload __load(input, input_big, parent = nil, index = nil)
3234
+ * Fill in the structure by loading it from +input+.
3235
+ * @param input [IO] the stream to load the structure from
3236
+ * @param input_big [Boolean] the endianness of +input+
3237
+ * @param parent [Structure] if given, the parent of the structure
3238
+ * @param index [Integer] if given, the structure is repeated and +index+ is the rank this structure
3239
+ * @return [Structure] self
3240
+ * @example
3241
+ * # Original Ruby implementation
3242
+ * def __load(input, input_big, parent = nil, index = nil)
3243
+ * __set_load_state(input, input_big, parent, index)
3244
+ * __load_fields
3245
+ * __unset_load_state
3246
+ * self
3247
+ * end
3248
+ */
3249
+ rb_define_method(cStructure, "__load", cStructure_load, -1);
3250
+ /**
3251
+ * @overload __dump(output, output_big, parent = nil, index = nil)
3252
+ * Dump the structure to +output+.
3253
+ * @param output [IO] the stream to dump the structure to
3254
+ * @param output_big [Boolean] the endianness of +output+
3255
+ * @param parent [Structure] if given, the parent of the structure
3256
+ * @param index [Integer] if given, the structure is repeated and +index+ is the rank this structure
3257
+ * @return [Structure] self
3258
+ * @example
3259
+ * # Original Ruby implementation
3260
+ * def __dump(output, output_big, parent = nil, index = nil)
3261
+ * __set_dump_state(output, output_big, parent, index)
3262
+ * __dump_fields
3263
+ * __unset_dump_state
3264
+ * self
3265
+ * end
3266
+ */
3267
+ rb_define_method(cStructure, "__dump", cStructure_dump, -1);
3268
+ /**
3269
+ * @overload __convert(input, output, input_big, output_big, parent = nil, index = nil)
3270
+ * Fill in the structure by loading it from +input+ and
3271
+ * dumping it to +output+.
3272
+ * @param input [IO] the stream to load the structure from
3273
+ * @param output [IO] the stream to dump the structure to
3274
+ * @param input_big [Boolean] the endianness of +input+
3275
+ * @param output_big [Boolean] the endianness of +output+
3276
+ * @param parent [Structure] if given, the parent of the structure
3277
+ * @param index [Integer] if given, the structure is repeated and +index+ is the rank this structure
3278
+ * @return [Structure] self
3279
+ * @example
3280
+ * # Original Ruby implementation
3281
+ * def __convert(input, output, input_big, output_big, parent = nil, index = nil)
3282
+ * __set_convert_state(input, output, input_big, output_big, parent, index)
3283
+ * __convert_fields
3284
+ * __unset_convert_state
3285
+ * self
3286
+ * end
3287
+ */
3288
+ rb_define_method(cStructure, "__convert", cStructure_convert, -1);
3289
+ /**
3290
+ * @overload __shape(offset = 0, parent = nil, index = nil, kind = DataShape)
3291
+ * Return the shape of the structure.
3292
+ * @param offset [Integer] the base position of the field
3293
+ * @param parent [Structure] if given, the parent of the structure
3294
+ * @param index [Integer] if given, the structure is repeated and +index+ is the rank this structure
3295
+ * @param kind [Class] the kind of structure to create
3296
+ * @return [kind] the the shape of the structure
3297
+ * @example
3298
+ * # Original Ruby implementation
3299
+ * def __shape(previous_offset = 0, parent = nil, index = nil, kind = DataShape)
3300
+ * __set_size_state(previous_offset, parent, index)
3301
+ * members = __shape_fields(kind)
3302
+ * __unset_size_state
3303
+ * return nil if members.values.compact.size <= 0
3304
+ * kind::new(members)
3305
+ * end
3306
+ */
3307
+ rb_define_method(cStructure, "__shape", cStructure_shape, -1);
3308
+
3309
+ /**
3310
+ * @overload load(input, input_big = LibBin::default_big?, parent = nil, index = nil, length = nil)
3311
+ * Load a structure from +input+.
3312
+ * @param input [IO] the stream to load the structure from
3313
+ * @param input_big [Boolean] the endianness of +input+
3314
+ * @param parent [Structure] if given, the parent of the structure
3315
+ * @param index [Integer] if given, the structure is repeated and +index+ is the rank this structure
3316
+ * @param length [Integer] if given, the length of the vector of structure
3317
+ * @return [Structure,Array<Structure>] a new strcuture, or
3318
+ * an array of structures if length was specified
3319
+ * @example
3320
+ * # Original Ruby implementation
3321
+ * def self.load(input, input_big = LibBin::default_big?, parent = nil, index = nil, length = nil)
3322
+ * if length
3323
+ * length.times.collect {
3324
+ * self.new.__load(input, input_big, parent, index)
3325
+ * }
3326
+ * else
3327
+ * self.new.__load(input, input_big, parent, index)
3328
+ * end
3329
+ * end
3330
+ */
3331
+ rb_define_singleton_method(cStructure, "load", cStructure_singl_load, -1);
3332
+ /**
3333
+ * @overload dump(value, output, output_big = LibBin::default_big?, parent = nil, index = nil, length = nil)
3334
+ * Dump a structure to +output+.
3335
+ * @param value [Structure,Array<Structure>] the value of structure to dump
3336
+ * @param output [IO] the stream to dump the structure to
3337
+ * @param output_big [Boolean] the endianness of +output+
3338
+ * @param parent [Structure] if given, the parent of the structure
3339
+ * @param index [Integer] if given, the structure is repeated and +index+ is the rank this structure
3340
+ * @param length [Integer] if given, the length of the vector of structure
3341
+ * @return [Structure,Array<Structure>] +value+
3342
+ * @example
3343
+ * # Original Ruby implementation
3344
+ * def self.dump(value, output, output_big = LibBin::default_big?, parent = nil, index = nil, length = nil)
3345
+ * if length
3346
+ * length.times.each { |i|
3347
+ * value[i].__dump(output, output_big, parent, index)
3348
+ * }
3349
+ * value
3350
+ * else
3351
+ * value.__dump(output, output_big, parent, index)
3352
+ * end
3353
+ * end */
3354
+ rb_define_singleton_method(cStructure, "dump", cStructure_singl_dump, -1);
3355
+ /**
3356
+ * @overload convert(input, output, input_big = LibBin::default_big?, output_big = !input_big, parent = nil, index = nil, length = nil)
3357
+ * Convert a structure by loading it from +input+ and
3358
+ * dumping it to +output+. Returns the loaded structure.
3359
+ * @param input [IO] the stream to load the structure from
3360
+ * @param output [IO] the stream to dump the structure to
3361
+ * @param input_big [Boolean] the endianness of +input+
3362
+ * @param output_big [Boolean] the endianness of +output+
3363
+ * @param parent [Structure] if given, the parent of the structure
3364
+ * @param index [Integer] if given, the structure is repeated and +index+ is the rank this structure
3365
+ * @param length [Integer] if given, the length of the vector of structure
3366
+ * @return [Structure,Array<Structure>] a new strcuture, or
3367
+ * an array of structures if length was specified
3368
+ * @example
3369
+ * # Original Ruby implementation
3370
+ * def self.convert(input, output, input_big = LibBin::default_big?, output_big = !input_big, parent = nil, index = nil, length = nil)
3371
+ * if length
3372
+ * length.times.collect {
3373
+ * self.new.__convert(input, output, input_big, output_big, parent, index)
3374
+ * }
3375
+ * else
3376
+ * self.new.__convert(input, output, input_big, output_big, parent, index)
3377
+ * end
3378
+ * end
3379
+ */
3380
+ rb_define_singleton_method(cStructure, "convert", cStructure_singl_convert, -1);
3381
+ /**
3382
+ * @overload shape(value, offset = 0, parent = nil, index = nil, kind = DataShape, length = nil)
3383
+ * Return the shape of the value.
3384
+ * @param value [Structure,Array<Structure>] the value of structure to get the shape of
3385
+ * @param offset [Integer] the base position of the field
3386
+ * @param parent [Structure] if given, the parent of the structure
3387
+ * @param index [Integer] if given, the structure is repeated and +index+ is the rank this structure
3388
+ * @param kind [Class] the kind of structure to create
3389
+ * @param length [Integer] if given, the length of the vector of structure
3390
+ * @return [kind] the the shape of the structure
3391
+ * @example
3392
+ * # Original Ruby implementation
3393
+ * def self.shape(value, previous_offset = 0, parent = nil, index = nil, kind = DataShape, length = nil)
3394
+ * if length
3395
+ * kind.new(length.times.collect { |i|
3396
+ * value[i].__shape(previous_offset, parent, index, kind)
3397
+ * })
3398
+ * else
3399
+ * value.__shape(previous_offset, parent, index, kind)
3400
+ * end
3401
+ * end
3402
+ */
3403
+ rb_define_singleton_method(cStructure, "shape", cStructure_singl_shape, -1);
1412
3404
  }
1413
3405
 
1414
3406
  static VALUE pghalf_from_string_p(VALUE self, VALUE str, VALUE pack_str) {
1415
3407
  (void)self;
1416
3408
  Check_Type(str, T_STRING);
1417
3409
  Check_Type(pack_str, T_STRING);
1418
- VALUE arr = rb_funcall(str, rb_intern("unpack"), 1, pack_str);
1419
- uint16_t val = NUM2USHORT(rb_funcall(arr, rb_intern("first"), 0));
1420
- union float_u res;
3410
+ VALUE arr = rb_funcall(str, id_unpack, 1, pack_str);
3411
+ uint16_t val = NUM2USHORT(rb_funcall(arr, id_first, 0));
1421
3412
 
1422
- res.i = pghalf_to_float(val);
1423
- return DBL2NUM(res.f);
3413
+ return DBL2NUM(pghalf_to_double(val));
1424
3414
  }
1425
3415
 
1426
3416
  static VALUE half_from_string_p(VALUE self, VALUE str, VALUE pack_str) {
1427
3417
  (void)self;
1428
3418
  Check_Type(str, T_STRING);
1429
3419
  Check_Type(pack_str, T_STRING);
1430
- VALUE arr = rb_funcall(str, rb_intern("unpack"), 1, pack_str);
1431
- uint16_t val = NUM2USHORT(rb_funcall(arr, rb_intern("first"), 0));
1432
- union float_u res;
3420
+ VALUE arr = rb_funcall(str, id_unpack, 1, pack_str);
3421
+ uint16_t val = NUM2USHORT(rb_funcall(arr, id_first, 0));
1433
3422
 
1434
- res.i = half_to_float(val);
1435
- return DBL2NUM(res.f);
3423
+ return DBL2NUM(half_to_double(val));
1436
3424
  }
1437
3425
 
1438
3426
  static VALUE pghalf_to_string_p(VALUE self, VALUE number, VALUE pack_str) {
1439
3427
  (void)self;
1440
- Check_Type(number, T_FLOAT);
1441
- union float_u val;
1442
- uint16_t res;
1443
-
1444
- val.f = NUM2DBL(number);
1445
- res = pghalf_from_float(val.i);
1446
- VALUE arr = rb_ary_new3(1, UINT2NUM(res) );
3428
+ Check_Type(pack_str, T_STRING);
3429
+ uint16_t res = pghalf_from_double(NUM2DBL(number));
3430
+ VALUE arr = rb_ary_new3(1, UINT2NUM(res));
1447
3431
 
1448
- return rb_funcall(arr, rb_intern("pack"), 1, pack_str);
3432
+ return rb_funcall(arr, id_pack, 1, pack_str);
1449
3433
  }
1450
3434
 
1451
3435
  static VALUE half_to_string_p(VALUE self, VALUE number, VALUE pack_str) {
1452
3436
  (void)self;
1453
- Check_Type(number, T_FLOAT);
1454
- union float_u val;
1455
- uint16_t res;
1456
-
1457
- val.f = NUM2DBL(number);
1458
- res = half_from_float(val.i);
1459
- VALUE arr = rb_ary_new3(1, UINT2NUM(res) );
3437
+ Check_Type(pack_str, T_STRING);
3438
+ uint16_t res = half_from_double(NUM2DBL(number));
3439
+ VALUE arr = rb_ary_new3(1, UINT2NUM(res));
1460
3440
 
1461
- return rb_funcall(arr, rb_intern("pack"), 1, pack_str);
3441
+ return rb_funcall(arr, id_pack, 1, pack_str);
1462
3442
  }
1463
3443
 
1464
- void Init_libbin_c() {
3444
+ static void define_cField(void) {
3445
+ id_gsub = rb_intern("gsub");
3446
+ id_eval = rb_intern("eval");
3447
+
3448
+ rb_field_eval_binding = rb_eval_string(
3449
+ "module LibBin; class Structure; lambda { binding }.call; end; end");
3450
+ rb_gc_register_mark_object(rb_field_eval_binding);
3451
+
3452
+ rb_re_dot_dot = rb_obj_freeze(rb_reg_new_str(rb_str_new_cstr("(?<![\\w.])\\.\\.(?=[\\\\.]|$)"), 0));
3453
+ rb_str___parent = rb_obj_freeze(rb_str_new_cstr("__parent"));
3454
+ rb_str_backslash = rb_obj_freeze(rb_str_new_cstr("\\"));
3455
+ rb_str_dot = rb_obj_freeze(rb_str_new_cstr("."));
3456
+ #ifdef HAVE_RB_RACTOR_MAKE_SHAREABLE
3457
+ rb_ractor_make_shareable(rb_re_dot_dot);
3458
+ rb_ractor_make_shareable(rb_str___parent);
3459
+ rb_ractor_make_shareable(rb_str_backslash);
3460
+ rb_ractor_make_shareable(rb_str_dot);
3461
+ #endif
3462
+ rb_gc_register_mark_object(rb_re_dot_dot);
3463
+ rb_gc_register_mark_object(rb_str___parent);
3464
+ rb_gc_register_mark_object(rb_str_backslash);
3465
+ rb_gc_register_mark_object(rb_str_dot);
3466
+
3467
+ cField = rb_define_class_under(cStructure, "Field", rb_cObject);
3468
+ rb_define_alloc_func(cField, cField_alloc);
3469
+ /**
3470
+ * @overload initialize(name, type, length, count, offset, sequence, condition, relative_offset, align, expect, null_offset)
3471
+ * @param name [Symbol, String, nil] the name of the field (or +nil+ for anonymous padding directives).
3472
+ * @param type [Class, String, Proc] the type of the field, as a Class, or
3473
+ * as a String or Proc that will be evaluated in the context of the
3474
+ * {Structure} instance.
3475
+ * @param length [nil, Integer, String, Proc] if given, consider the field a
3476
+ * vector of the type. The length is either a constant Integer of a
3477
+ * String or Proc that will be evaluated in the context of the
3478
+ * {Structure} instance.
3479
+ * @param count [nil, Integer, String, Proc] if given, consider the field is
3480
+ * repeated count times. The count is either a constant Integer of a
3481
+ * String or Proc that will be evaluated in the context of the
3482
+ * {Structure} instance.
3483
+ * @param offset [nil, integer, String, Proc] if given, the absolute offset in
3484
+ * the file, or the offset from the parent position, where the field can
3485
+ * be found. See relative offset. The offset is either a constant
3486
+ * Integer of a String or Proc that will be evaluated in the context
3487
+ * of the {Structure} instance.
3488
+ * @param sequence [Boolean] if true, +type+, +length+, +offset+, and
3489
+ * +condition+ are evaluated for each repetition.
3490
+ * @param condition [nil, String, Proc] if given, the field, or repetition of the
3491
+ * field can be conditionally present. The condition will be evaluated in
3492
+ * the context of the {Structure} instance.
3493
+ * @param relative_offset [Boolean] consider the +offset+ relative to
3494
+ * the field +parent+.
3495
+ * @param align [nil, Integer] if given, align the field. If given as an
3496
+ * Integer it must be a power of 2. Else the field is aligned to the
3497
+ * field's type preferred alignment
3498
+ * @param expect [nil, Proc, Object] if given as a Proc the proc must
3499
+ * evaluate to a truthy value or an exception will be raised. Else, the
3500
+ * object will be tested for equality, and an exception will be raised if
3501
+ * objects were not equal. Proc is evaluated in the context of the {Structure}
3502
+ * instance and #__value will be set. Each repetition is validated.
3503
+ * @param null_offset [nil, false, Integer] offset sentinel treated as absent.
3504
+ * @return [Field] new Field
3505
+ */
3506
+ rb_define_method(cField, "initialize", cField_initialize, 11);
3507
+ DEFINE_FIELD_STATE_GETTER(name);
3508
+ DEFINE_FIELD_STATE_GETTER(type);
3509
+ DEFINE_FIELD_STATE_GETTER(length);
3510
+ DEFINE_FIELD_STATE_GETTER(count);
3511
+ DEFINE_FIELD_STATE_GETTER(offset);
3512
+ DEFINE_FIELD_STATE_GETTER_BOOL(sequence);
3513
+ DEFINE_FIELD_STATE_GETTER(condition);
3514
+ DEFINE_FIELD_STATE_GETTER_BOOL(relative_offset);
3515
+ DEFINE_FIELD_STATE_GETTER(align);
3516
+ DEFINE_FIELD_STATE_GETTER(expect);
3517
+ DEFINE_FIELD_STATE_GETTER(null_offset);
3518
+ }
3519
+
3520
+ void Init_libbin_c(void) {
3521
+ #ifdef HAVE_RB_EXT_RACTOR_SAFE
3522
+ rb_ext_ractor_safe(true);
3523
+ #endif
3524
+ rb_require("stringio");
1465
3525
  mLibBin = rb_define_module("LibBin");
3526
+
3527
+ eLibBinError = rb_define_class_under(mLibBin, "Error", rb_eRuntimeError);
3528
+ eLibBinEOFError = rb_define_class_under(mLibBin, "EOFError", eLibBinError);
3529
+ eLibBinValidationError = rb_define_class_under(mLibBin, "ValidationError", eLibBinError);
3530
+ eLibBinAlignmentError = rb_define_class_under(mLibBin, "AlignmentError", eLibBinError);
3531
+
3532
+ id_ivar_structure = rb_intern("@structure");
3533
+ id_ivar_field = rb_intern("@field");
3534
+ id_ivar_offset = rb_intern("@offset");
3535
+ id_ivar_index = rb_intern("@index");
3536
+
3537
+ /**
3538
+ * @overload half_from_string(str, unpack_str)
3539
+ * Load (unpacks) a half precision floating point.
3540
+ * @param str [String] the strin to read the number from
3541
+ * @param unpack_str [String] the unpack format of the underlying 16bit integer
3542
+ * @return [Float] the ruby representation of the value
3543
+ * @example
3544
+ * # Read a half precision floating point value stored in 'str' in little endian fashion
3545
+ * value = half_from_string(str, "S<")
3546
+ */
1466
3547
  rb_define_module_function(mLibBin, "half_from_string", half_from_string_p, 2);
3548
+ /**
3549
+ * @overload half_to_string(value, pack_str)
3550
+ * Convert a Numeric value to a half precision floating point and pack it into a string.
3551
+ * @param value [Numeric] the number to convert
3552
+ * @param pack_str [String] the pack format to store the underlying 16 bit integer representation of the value
3553
+ * @return [String] the packed half precision value
3554
+ * @example
3555
+ * # Stores a number as a half precision floating point value in a big endian fashion
3556
+ * str = half_to_string(value, "S>")
3557
+ */
1467
3558
  rb_define_module_function(mLibBin, "half_to_string", half_to_string_p, 2);
3559
+ /**
3560
+ * @overload pghalf_from_string(str, unpack_str)
3561
+ * Load (unpacks) a half precision floating point as used by PlatinumGames in some formats.
3562
+ * @param str [String] the strin to read the number from
3563
+ * @param unpack_str [String] the unpack format of the underlying 16bit integer
3564
+ * @return [Float] the ruby representation of the value
3565
+ * @example
3566
+ * # Read a half precision floating point value stored in 'str' in little endian fashion
3567
+ * half_from_string(str, "S<")
3568
+ */
1468
3569
  rb_define_module_function(mLibBin, "pghalf_from_string", pghalf_from_string_p, 2);
3570
+ /**
3571
+ * @overload pghalf_to_string(value, pack_str)
3572
+ * Convert a Numeric value to a half precision floating point as used by PlatinumGames in some formats, and pack it into a string.
3573
+ * @param value [Numeric] the number to convert
3574
+ * @param pack_str [String] the pack format to store the underlying 16 bit integer representation of the value
3575
+ * @return [String] the packed half precision value
3576
+ * @example
3577
+ * # Stores a number as a half precision floating point value in a big endian fashion
3578
+ * str = half_to_string(value, "S>")
3579
+ */
1469
3580
  rb_define_module_function(mLibBin, "pghalf_to_string", pghalf_to_string_p, 2);
1470
- cDataShape = rb_define_class_under(mLibBin, "DataShape", rb_cObject);
3581
+ cDataRange = rb_define_class_under(mLibBin, "DataRange", rb_cObject);
3582
+ cDataShape = rb_define_class_under(mLibBin, "DataShape", cDataRange);
3583
+ define_cStructure();
1471
3584
  define_cField();
1472
- define_cDataConverter();
1473
3585
  define_cScalar();
1474
3586
  }