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.
@@ -1,199 +1,475 @@
1
+ require 'stringio'
2
+ require_relative 'data_shape'
3
+
1
4
  module LibBin
2
5
 
3
- module RangeRefinement
4
- refine Range do
5
- def +(other)
6
- return other.dup unless min
7
- return self.dup unless other.min
8
- Range::new(min <= other.min ? min : other.min,
9
- max >= other.max ? max : other.max)
6
+ # @abstract This class is used to describe a binary data structure
7
+ # composed of different fields.
8
+ class Structure
9
+
10
+ # @!parse
11
+ # # Field class that is instantiated to describe a structure field.
12
+ # class Field
13
+ # attr_reader :name
14
+ # attr_reader :type
15
+ # attr_reader :length
16
+ # attr_reader :count
17
+ # attr_reader :offset
18
+ # attr_reader :condition
19
+ # attr_reader :align
20
+ # attr_reader :expect
21
+ #
22
+ # # @method relative_offset?
23
+ # # Returns +true+ if the field offset should be relative to its parent.
24
+ # # @return [Boolean] field offset is relative
25
+ #
26
+ # # @method sequence?
27
+ # # Returns +true+ if the field is a sequence
28
+ # # @return [Boolean] field is a sequence
29
+ # end
30
+
31
+ def self.resolve_align(type, align)
32
+ if type.respond_to?(:always_align) && type.always_align
33
+ al = type.align
34
+ align = align.kind_of?(Integer) && align >= al ? align : al
35
+ end
36
+ if align == true
37
+ # Automatic alignment not supported for dynamic types
38
+ raise LibBin::AlignmentError, "alignment is unsupported for dynamic types" unless type.respond_to?(:align)
39
+ align = type.align
40
+ elsif align
41
+ if !align.kind_of?(Integer) || align <= 0 || (align - 1) & align != 0
42
+ raise LibBin::AlignmentError, "alignment must be a power of 2"
43
+ end
10
44
  end
45
+ align
11
46
  end
12
- end
47
+ private_class_method :resolve_align
13
48
 
14
- class DataShape
15
- using RangeRefinement
16
- attr_reader :range
17
- attr_reader :members
49
+ FIELD_TYPE_UNSET = Object.new.freeze
50
+ private_constant :FIELD_TYPE_UNSET
51
+
52
+ # @!visibility private
53
+ def self.__promoted_accessors
54
+ list = []
55
+ seen = {}
56
+ @fields.each do |f|
57
+ next unless f.name
58
+ fname = f.name.to_sym
59
+ if fname.to_s.match?(/\A__(?:anon|union)_\d+\z/) && f.type.is_a?(Class) && f.type < Structure
60
+ f.type.__promoted_accessors.each do |m|
61
+ next if seen[m]
62
+ seen[m] = true
63
+ list << m
64
+ end
65
+ elsif !seen[fname]
66
+ seen[fname] = true
67
+ list << fname
68
+ end
69
+ end
70
+ list
71
+ end
18
72
 
19
- def method_missing(m, *arg, &block)
20
- return @members[m] if @members && @members[m]
21
- super
73
+ def self.promote_embedded_accessors(hidden_name, klass)
74
+ ivar = :"@#{hidden_name}"
75
+ klass.__promoted_accessors.each do |mname|
76
+ msetter = :"#{mname}="
77
+ define_method(mname) do
78
+ sub = instance_variable_get(ivar)
79
+ sub.nil? ? nil : sub.public_send(mname)
80
+ end
81
+ define_method(msetter) do |val|
82
+ sub = instance_variable_get(ivar) || instance_variable_set(ivar, klass.new)
83
+ sub.public_send(msetter, val)
84
+ end
85
+ end
22
86
  end
87
+ private_class_method :promote_embedded_accessors
23
88
 
24
- def initialize(*args)
25
- if args.length == 2
26
- @range = Range::new(args[0], args[1])
27
- @members = nil
28
- else
29
- @members = args[0]
30
- if @members.kind_of?(Hash)
31
- @range = @members.values.compact.collect(&:range).reduce(:+)
89
+ # Must stay in the same file as `attr_accessor name` inside `Structure.field`
90
+ # so `is_default_accessor_method` recognizes default C ivar fast-path accessors.
91
+ __set_data_types_file(__FILE__)
92
+
93
+ # Define a new field in the structure (or embed an anonymous {Structure}/{Union}
94
+ # when given a single class argument).
95
+ # @param name [Symbol, String, Class, nil] field name, or embedded class
96
+ # @param type [Class, String, Proc] the type of the field, as a Class, or
97
+ # as a String or Proc that will be evaluated in the context of the
98
+ # {Structure} instance.
99
+ # @param length [Integer, String, Proc] if given, consider the field a
100
+ # vector of the type.
101
+ # @param count [Integer, String, Proc] if given, consider the field repeated
102
+ # +count+ times.
103
+ # @param offset [Integer, String, Proc] stream offset (absolute, or relative to +parent+).
104
+ # @param sequence [Boolean] if true, +type+, +length+, +offset+, and
105
+ # +condition+ are evaluated for each repetition.
106
+ # @param condition [String, Proc] predicate controlling field presence.
107
+ # @param relative_offset [Boolean] consider +offset+ relative to +parent+.
108
+ # @param align [Boolean, Integer] alignment requirement (power of 2, or +true+ for type alignment).
109
+ # @param expect [Proc, Object] validator proc or expected equality value.
110
+ # @param null_offset [Integer, false, nil] offset sentinel treated as absent (default +0+).
111
+ # @return self
112
+ def self.field(name, type = FIELD_TYPE_UNSET, length: nil, count: nil, offset: nil,
113
+ sequence: false, condition: nil, relative_offset: false,
114
+ align: false, expect: nil, null_offset: 0)
115
+ if type.equal?(FIELD_TYPE_UNSET)
116
+ if name.is_a?(Class) && name < LibBin::Structure
117
+ type = name
118
+ name = nil
32
119
  else
33
- @range = @members.compact.collect(&:range).reduce(:+)
120
+ raise ArgumentError, "wrong number of arguments (given 1, expected 2)"
34
121
  end
35
122
  end
123
+
124
+ if name.nil? && type.is_a?(Class) && type < LibBin::Structure
125
+ if count || length
126
+ raise ArgumentError, "anonymous embedded structure/union cannot have count or length"
127
+ end
128
+ hidden = (type <= LibBin::Union) ? :"__union_#{@fields.length}" : :"__anon_#{@fields.length}"
129
+ align = resolve_align(type, align)
130
+ set_fields_array(@fields + [Field::new(hidden, type, nil, nil, offset, sequence,
131
+ condition, relative_offset, align, expect,
132
+ null_offset)])
133
+ attr_accessor hidden
134
+ promote_embedded_accessors(hidden, type)
135
+ return self
136
+ end
137
+
138
+ align = resolve_align(type, align)
139
+ set_fields_array(@fields + [Field::new(name, type, length, count, offset, sequence,
140
+ condition, relative_offset, align, expect,
141
+ null_offset)])
142
+ if name
143
+ attr_accessor name
144
+ else
145
+ Structure.__bump_override_gen
146
+ end
147
+ self
36
148
  end
37
149
 
38
- def first
39
- @range.first
150
+ class << self
151
+ alias register_field field
40
152
  end
41
153
 
42
- def last
43
- @range.last
154
+ # @!parse
155
+ # # @abstract Parent class for scalars
156
+ # class Scalar
157
+ # end
158
+
159
+ # @!macro attach
160
+ # @!parse
161
+ # # $4
162
+ # class $1 < Scalar
163
+ # # @method align
164
+ # # @scope class
165
+ # # Returns the alignment of {$1}.
166
+ # # @return [Integer] the byte boundary to align the type to.
167
+ # # @method shape(value = nil, offset = 0, parent = nil, index = nil, kind = DataShape, length = nil)
168
+ # # @scope class
169
+ # # Returns the shape of a field of type {$1}
170
+ # # @param value [Object] ignored.
171
+ # # @param offset [Integer] start of the shape.
172
+ # # @param parent [Structure] ignored.
173
+ # # @param index [Integer] ignored.
174
+ # # @param kind [Class] shape class. Will be instantiated through
175
+ # # new with the +offset+ and <tt>offset + sizeof($3) * length - 1</tt>.
176
+ # # @param length [Integer] if given the length of the vector. Else
177
+ # # the length is considered to be 1.
178
+ # # @return [kind] a new instance of +kind+
179
+ # # @method size(value = nil, offset = 0, parent = nil, index = nil, length = nil)
180
+ # # @scope class
181
+ # # Returns the size of a field of type {$1}.
182
+ # # @param value [Object] ignored.
183
+ # # @param offset [Integer] ignored.
184
+ # # @param parent [Structure] ignored.
185
+ # # @param index [Integer] ignored.
186
+ # # @param length [Integer] if given the length of the vector. Else
187
+ # # the length is considered to be 1.
188
+ # # @return [Integer] the type <tt>sizeof($3) * length</tt>.
189
+ # # @method load(input, input_big = LibBin::default_big?, parent = nil, index = nil, length = nil)
190
+ # # @scope class
191
+ # # Load a field of type {$1} from +input+, and return it.
192
+ # # @param input [IO] the stream to load the field from.
193
+ # # @param input_big [Boolean] the endianness of +input+
194
+ # # @param parent [Structure] ignored.
195
+ # # @param index [Integer] ignored.
196
+ # # @param length [Integer] if given the length of the vector. Else
197
+ # # the length is considered to be 1.
198
+ # # @return [Numeric, Array<Numeric>] the Ruby representation of the
199
+ # # type, or the Array representation of the vector if +length+
200
+ # # was specified
201
+ # # @method dump(value, output, output_big = LibBin::default_big?, parent = nil, index = nil, length = nil)
202
+ # # @scope class
203
+ # # Dump a field of class {$1} to +output+.
204
+ # # @param value [Numeric, Array<Numeric>] the Ruby representation
205
+ # # of the type, or the Array representation of the vector if
206
+ # # +length+ is specified.
207
+ # # @param output [IO] the stream to dump the field to.
208
+ # # @param output_big [Boolean] the endianness of +output+.
209
+ # # @param parent [Structure] ignored.
210
+ # # @param index [Integer] ignored.
211
+ # # @param length [Integer] if given the length of the vector. Else
212
+ # # the length is considered to be 1.
213
+ # # @return [nil]
214
+ # # @method convert(input, output, input_big = LibBin::default_big?, output_big = !input_big, parent = nil, index = nil, length = nil)
215
+ # # @scope class
216
+ # # Convert a field of class {$1} by loading it from +input+ and
217
+ # # dumping it to +output+. Returns the loaded field.
218
+ # # @param input [IO] the stream to load the field from.
219
+ # # @param output [IO] the stream to dump the field to.
220
+ # # @param input_big [Boolean] the endianness of +input+
221
+ # # @param output_big [Boolean] the endianness of +output+.
222
+ # # @param parent [Structure] ignored.
223
+ # # @param index [Integer] ignored.
224
+ # # @param length [Integer] if given the length of the vector. Else
225
+ # # the length is considered to be 1.
226
+ # # @return [Numeric, Array<Numeric>] the Ruby representation of the
227
+ # # type, or the Array representation of the vector if +length+
228
+ # # was specified
229
+ # end
230
+ # @!method $2 method_signature(name, length: nil, count: nil, offset: nil, sequence: false, condition: nil, relative_offset: false, align: false)
231
+ # @!scope class
232
+ # Create a new field of type {$1} and name +name+. See {field} for options.
233
+ # @return self
234
+ #
235
+ def self.define_scalar_constructor(klassname, name, _mapped_type, _description)
236
+ klass = const_get(klassname)
237
+ define_singleton_method(name) do |field_name, **opts|
238
+ self.field(field_name, klass, **opts)
239
+ end
44
240
  end
241
+ private_class_method :define_scalar_constructor
242
+
243
+ # @!group Scalars
244
+ define_scalar_constructor "Int8", :int8, :int8_t, "A signed 8 bit integer"
245
+ define_scalar_constructor "UInt8", :uint8, :uint8_t, "An unsigned 8 bit integer"
246
+ define_scalar_constructor "Int16", :int16, :int16_t, "A signed 16 bit integer"
247
+ define_scalar_constructor "Int16_LE", :int16_le, :int16_t, "A signed little endian 16 bit integer"
248
+ define_scalar_constructor "Int16_BE", :int16_be, :int16_t, "A signed big endian 16 bit integer"
249
+ define_scalar_constructor "UInt16", :uint16, :uint16_t, "An unsigned 16 bit integer"
250
+ define_scalar_constructor "UInt16_LE", :uint16_le, :uint16_t, "An unsigned little endian 16 bit integer"
251
+ define_scalar_constructor "UInt16_BE", :uint16_be, :uint16_t, "An unsigned big endian 16 bit integer"
252
+ define_scalar_constructor "Int32", :int32, :int32_t, "A signed 32 bit integer"
253
+ define_scalar_constructor "Int32_LE", :int32_le, :int32_t, "A signed little endian 32 bit integer"
254
+ define_scalar_constructor "Int32_BE", :int32_be, :int32_t, "A signed big endian 32 bit integer"
255
+ define_scalar_constructor "UInt32", :uint32, :uint32_t, "An unsigned 32 bit integer"
256
+ define_scalar_constructor "UInt32_LE", :uint32_le, :uint32_t, "An unsigned little endian 32 bit integer"
257
+ define_scalar_constructor "UInt32_BE", :uint32_be, :uint32_t, "An unsigned big endian 32 bit integer"
258
+ define_scalar_constructor "Int64", :int64, :int64_t, "A signed 64 bit integer"
259
+ define_scalar_constructor "Int64_LE", :int64_le, :int64_t, "A signed little endian 64 bit integer"
260
+ define_scalar_constructor "Int64_BE", :int64_be, :int64_t, "A signed big endian 64 bit integer"
261
+ define_scalar_constructor "UInt64", :uint64, :uint64_t, "An unsigned 64 bit integer"
262
+ define_scalar_constructor "UInt64_LE", :uint64_le, :uint64_t, "An unsigned little endian 64 bit integer"
263
+ define_scalar_constructor "UInt64_BE", :uint64_be, :uint64_t, "An unsigned big endian 64 bit integer"
264
+ define_scalar_constructor "Flt", :float, :float, "A single precision floating point scalar"
265
+ define_scalar_constructor "Flt_LE", :float_le, :float, "A single precision little endian floating point scalar"
266
+ define_scalar_constructor "Flt_BE", :float_be, :float, "A single precision big endian floating point scalar"
267
+ define_scalar_constructor "Double", :double, :double, "A double precision floating point scalar"
268
+ define_scalar_constructor "Double_LE", :double_le, :double, "A double precision little endian floating point scalar"
269
+ define_scalar_constructor "Double_BE", :double_be, :double, "A double precision big endian floating point scalar"
270
+ define_scalar_constructor "Half", :half, :half, "A half precision floating point scalar"
271
+ define_scalar_constructor "Half_LE", :half_le, :half, "A half precision little endian floating point scalar"
272
+ define_scalar_constructor "Half_BE", :half_be, :half, "A half precision big endian floating point scalar"
273
+ define_scalar_constructor "PGHalf", :pghalf, :pghalf, "A half precision floating point scalar as used by PlatinumGames in certain formats"
274
+ define_scalar_constructor "PGHalf_LE", :pghalf_le, :pghalf, "A half precision little endian floating point scalar as used by PlatinumGames in certain formats"
275
+ define_scalar_constructor "PGHalf_BE", :pghalf_be, :pghalf, "A half precision big endian floating point scalar as used by PlatinumGames in certain formats"
45
276
 
46
- def size
47
- @range.size
277
+ # @!parse
278
+ # # A string type, can be NULL terminated or have an arbitrary length.
279
+ # class Str < Scalar
280
+ # end
281
+
282
+ # Create a new field of type {Str} (or {ZStr} if +trim: true+) and name +name+. See {field} for options.
283
+ # @return self
284
+ def self.string(field_name, length = nil, trim: false, **opts)
285
+ self.field(field_name, trim ? ZStr : Str, length: length, **opts)
48
286
  end
49
287
 
50
- end
288
+ # Create a new field of type {ZStr} (NUL-terminated or NUL-trimmed string) and name +name+. See {field} for options.
289
+ # @return self
290
+ def self.zstring(field_name, length = nil, **opts)
291
+ self.field(field_name, ZStr, length: length, **opts)
292
+ end
51
293
 
52
- class DataRange
53
- using RangeRefinement
54
- attr_reader :range
294
+ FILL_CLASS_CACHES = { Skip => {}, AlignTo => {} }.freeze
295
+ private_constant :FILL_CLASS_CACHES
55
296
 
56
- def initialize(*args)
57
- if args.length == 2
58
- @range = Range::new(args[0], args[1])
59
- else
60
- if args[0].kind_of?(Hash)
61
- @range = args[0].values.compact.collect(&:range).reduce(:+)
62
- else
63
- @range = args[0].compact.collect(&:range).reduce(:+)
64
- end
65
- end
297
+ def self.fill_class_for(base, fill)
298
+ raise ArgumentError, "fill must be an Integer in 0..255: #{fill.inspect}" unless fill.is_a?(Integer) && fill >= 0 && fill <= 255
299
+ return base if fill == 0
300
+
301
+ FILL_CLASS_CACHES[base][fill] ||= Class.new(base) { |c| c.instance_variable_set(:@fill, fill) }
66
302
  end
303
+ private_class_method :fill_class_for
67
304
 
68
- def first
69
- @range.first
305
+ # Skip +length+ bytes without declaring a named field.
306
+ # @param length [Integer, String, Proc] number of bytes to skip / zero-fill
307
+ # @param fill [Integer] fill byte used on dump (0..255)
308
+ # @return self
309
+ def self.skip(length, fill: 0, **opts)
310
+ klass = Structure.send(:fill_class_for, Skip, fill)
311
+ self.field(nil, klass, length: length, **opts)
70
312
  end
71
313
 
72
- def last
73
- @range.last
314
+ # Pad or skip to the next +alignment+ byte boundary (power of 2).
315
+ # @param alignment [Integer] byte boundary (must be a positive power of 2)
316
+ # @param fill [Integer] fill byte used on dump (0..255)
317
+ # @return self
318
+ def self.align_to(alignment, fill: 0, condition: nil)
319
+ unless alignment.kind_of?(Integer) && alignment > 0 && (alignment - 1) & alignment == 0
320
+ raise LibBin::AlignmentError, "alignment must be a power of 2"
321
+ end
322
+ klass = Structure.send(:fill_class_for, AlignTo, fill)
323
+ self.field(nil, klass, length: alignment, condition: condition)
74
324
  end
75
325
 
76
- def size
77
- @range.size
326
+ class << self
327
+ alias pad_to align_to
78
328
  end
79
329
 
80
330
  end
331
+ end
332
+
333
+ require_relative 'utf16'
334
+ require_relative 'enum'
335
+ require_relative 'bitfield'
336
+ require_relative 'union'
337
+
338
+ module LibBin
339
+ class Structure
340
+
341
+ CHOICE_UNSET = Object.new.freeze
342
+ private_constant :CHOICE_UNSET
343
+
344
+ # Shorthand symbol mapping for built-in types used by {choice} and {resolve_type}.
345
+ TYPE_MAP = {
346
+ int8: Int8, uint8: UInt8,
347
+ int16: Int16, int16_le: Int16_LE, int16_be: Int16_BE,
348
+ uint16: UInt16, uint16_le: UInt16_LE, uint16_be: UInt16_BE,
349
+ int32: Int32, int32_le: Int32_LE, int32_be: Int32_BE,
350
+ uint32: UInt32, uint32_le: UInt32_LE, uint32_be: UInt32_BE,
351
+ int64: Int64, int64_le: Int64_LE, int64_be: Int64_BE,
352
+ uint64: UInt64, uint64_le: UInt64_LE, uint64_be: UInt64_BE,
353
+ float: Flt, float_le: Flt_LE, float_be: Flt_BE,
354
+ double: Double, double_le: Double_LE, double_be: Double_BE,
355
+ half: Half, half_le: Half_LE, half_be: Half_BE,
356
+ pghalf: PGHalf, pghalf_le: PGHalf_LE, pghalf_be: PGHalf_BE,
357
+ string: Str, zstring: ZStr,
358
+ utf16: UTF16, utf16_le: UTF16_LE, utf16_be: UTF16_BE
359
+ }.freeze
81
360
 
82
- # class Field
83
- # attr_reader :name,
84
- # :type,
85
- # :length,
86
- # :count,
87
- # :offset,
88
- # :sequence,
89
- # :condition
90
- #
91
- # def sequence?
92
- # @sequence
93
- # end
94
- #
95
- # def relative_offset?
96
- # @relative_offset
97
- # end
98
- #
99
- # def initialize(name, type, length, count, offset, sequence, condition, relative_offset)
100
- # @name = name
101
- # @type = type
102
- # @length = length
103
- # @count = count
104
- # @offset = offset
105
- # @sequence = sequence
106
- # @condition = condition
107
- # @relative_offset = relative_offset
108
- # end
109
- #
110
- # end
111
-
112
- class DataConverter
113
-
114
- SCALAR_TYPES = {
115
- :c => [:Int8, :int8],
116
- :C => [:UInt8, :uint8],
117
- :s => [:Int16, :int16],
118
- :"s<" => [:Int16_LE, :int16_le],
119
- :"s>" => [:Int16_BE, :int16_be],
120
- :S => [:UInt16, :uint16],
121
- :"S<" => [:UInt16_LE, :uint16_le],
122
- :"S>" => [:UInt16_BE, :uint16_be],
123
- :v => [:UInt16_LE, :uint16_le],
124
- :n => [:UInt16_BE, :uint16_be],
125
- :l => [:Int32, :int32],
126
- :"l<" => [:Int32_LE, :int32_le],
127
- :"l>" => [:Int32_BE, :int32_be],
128
- :L => [:UInt32, :uint32],
129
- :"L<" => [:UInt32_LE, :uint32_le],
130
- :"L>" => [:UInt32_BE, :uint32_be],
131
- :V => [:UInt32_LE, :uint32_le],
132
- :N => [:UInt32_BE, :uint32_be],
133
- :q => [:Int64, :int64],
134
- :"q<" => [:Int64_LE, :int64_le],
135
- :"q>" => [:Int64_BE, :int64_be],
136
- :Q => [:UInt64, :uint64],
137
- :"Q<" => [:UInt64_LE, :uint64_le],
138
- :"Q>" => [:UInt64_BE, :uint64_be],
139
- :F => [:Flt, :float],
140
- :e => [:Flt_LE, :float_le],
141
- :g => [:Flt_BE, :float_be],
142
- :D => [:Double, :double],
143
- :E => [:Double_LE, :double_le],
144
- :G => [:Double_BE, :double_be],
145
- :half => [:Half, :half],
146
- :half_le => [:Half_LE, :half_le],
147
- :half_be => [:Half_BE, :half_be],
148
- :pghalf => [:PGHalf, :pghalf],
149
- :pghalf_le => [:PGHalf_LE, :pghalf_le],
150
- :pghalf_be => [:PGHalf_BE, :pghalf_be]
151
- }
152
-
153
- def self.register_field(field, type, length: nil, count: nil, offset: nil, sequence: false, condition: nil, relative_offset: false)
154
- if type.kind_of?(Symbol)
155
- if type[0] == 'a'
156
- real_type = Str
361
+ # Resolve a type class or shorthand symbol (or nil) to a LibBin type or nil.
362
+ def self.resolve_type(t)
363
+ return nil if t.nil?
364
+ return TYPE_MAP.fetch(t) { raise ArgumentError, "unknown LibBin type symbol: #{t.inspect}" } if t.is_a?(Symbol)
365
+ t
366
+ end
367
+
368
+ # Declare a field whose type is selected dynamically based on +tag+.
369
+ # @param name [Symbol, String] name of the field
370
+ # @param tag [Symbol, String, Proc] discriminator field name, path expression, or Proc
371
+ # @param cases [Hash] mapping of discriminator values (or === matchers such as Range) to types or nil
372
+ # @param default [Class, Symbol, nil] fallback type when +tag+ does not match +cases+
373
+ # @return self
374
+ def self.choice(name, tag, cases, default: CHOICE_UNSET, condition: nil, align: false, **opts)
375
+ eval_tag =
376
+ case tag
377
+ when Symbol
378
+ sym = tag
379
+ proc { send(sym) }
380
+ when String
381
+ __preprocess_expression(tag)
382
+ when Proc
383
+ tag
157
384
  else
158
- real_type = const_get(SCALAR_TYPES[type][0])
385
+ raise ArgumentError, "choice tag must be a Symbol, String, or Proc (got #{tag.inspect})"
386
+ end
387
+
388
+ exact_cases = {}
389
+ match_cases = []
390
+ cases.each do |k, v|
391
+ rt = resolve_type(v)
392
+ if k.is_a?(Range) || k.is_a?(Proc) || k.is_a?(Module) || k.is_a?(Regexp)
393
+ match_cases << [k, rt]
394
+ else
395
+ exact_cases[k] = rt
159
396
  end
160
- else
161
- real_type = type
162
397
  end
163
- @fields.push(Field::new(field, real_type, length, count, offset, sequence, condition, relative_offset))
164
- attr_accessor field
165
- end
398
+ resolved_default = default.equal?(CHOICE_UNSET) ? CHOICE_UNSET : resolve_type(default)
166
399
 
167
- def self.create_scalar_accessor(symbol)
168
- klassname, name = SCALAR_TYPES[symbol]
169
- eval <<EOF
170
- def self.#{name}(field, length: nil, count: nil, offset: nil, sequence: false, condition: nil, relative_offset: false)
171
- @fields.push(Field::new(field, #{klassname}, length, count, offset, sequence, condition, relative_offset))
172
- attr_accessor field
400
+ resolver = lambda do |obj|
401
+ tv = obj.instance_exec(&eval_tag)
402
+ if exact_cases.key?(tv)
403
+ exact_cases[tv]
404
+ elsif (found = match_cases.find { |matcher, _| matcher === tv })
405
+ found[1]
406
+ elsif !resolved_default.equal?(CHOICE_UNSET)
407
+ resolved_default
408
+ else
409
+ raise LibBin::Error, "no matching choice case for #{name}: #{tv.inspect}"
410
+ end
411
+ end
412
+
413
+ all_types = exact_cases.values + match_cases.map(&:last)
414
+ all_types << resolved_default unless resolved_default.equal?(CHOICE_UNSET)
415
+ has_nil_branch = all_types.any?(&:nil?)
416
+
417
+ resolved_align =
418
+ if align == true
419
+ non_nil = all_types.compact
420
+ if non_nil.empty? || !non_nil.all? { |t| t.respond_to?(:align) }
421
+ raise LibBin::AlignmentError, "alignment is unsupported for dynamic types"
422
+ end
423
+ m = non_nil.map(&:align).max || 0
424
+ m > 0 ? m : false
425
+ else
426
+ align
427
+ end
428
+
429
+ combined_condition =
430
+ if has_nil_branch
431
+ user_cond = condition.is_a?(String) ? __preprocess_expression(condition) : condition
432
+ proc do
433
+ ok = user_cond.is_a?(Proc) ? instance_exec(&user_cond) : (user_cond.nil? || user_cond)
434
+ ok && !resolver.call(self).nil?
435
+ end
436
+ else
437
+ condition
438
+ end
439
+
440
+ self.field(name, proc { resolver.call(self) }, condition: combined_condition, align: resolved_align, **opts)
173
441
  end
174
- EOF
442
+
443
+ def self.define_embedded_type(name_or_klass, base_klass, error_msg, strict_subclass, **opts, &block)
444
+ if block
445
+ name = name_or_klass
446
+ klass = Class.new(base_klass, &block)
447
+ elsif name_or_klass.is_a?(Class) &&
448
+ (strict_subclass ? name_or_klass < base_klass : name_or_klass <= base_klass)
449
+ name = nil
450
+ klass = name_or_klass
451
+ else
452
+ raise ArgumentError, error_msg
453
+ end
454
+ self.field(name, klass, **opts)
175
455
  end
456
+ private_class_method :define_embedded_type
176
457
 
177
- [:c,
178
- :C,
179
- :s, :"s<", :"s>",
180
- :S, :"S<", :"S>",
181
- :l, :"l<", :"l>",
182
- :L, :"L<", :"L>",
183
- :q, :"q<", :"q>",
184
- :Q, :"Q<", :"Q>",
185
- :F, :e, :g,
186
- :D, :E, :G,
187
- :half, :half_le, :half_be,
188
- :pghalf, :pghalf_le, :pghalf_be].each { |c|
189
- create_scalar_accessor(c)
190
- }
458
+ # Define an inline sub-structure field (when +name_or_klass+ is a Symbol/String),
459
+ # or an anonymous embedded structure (when +name_or_klass+ is +nil+ or a {Structure} class).
460
+ # @return self
461
+ def self.struct(name_or_klass = nil, **opts, &block)
462
+ define_embedded_type(name_or_klass, LibBin::Structure,
463
+ "struct requires a block or a LibBin::Structure subclass", true, **opts, &block)
464
+ end
191
465
 
192
- def self.string( field, length = nil, count: nil, offset: nil, sequence: false, condition: nil, relative_offset: false)
193
- @fields.push(Field::new(field, Str, length, count, offset, sequence, condition, relative_offset))
194
- attr_accessor field
466
+ # Define a union field (when +name_or_klass+ is a Symbol/String),
467
+ # or an anonymous embedded union (when +name_or_klass+ is +nil+ or a {Union} class).
468
+ # @return self
469
+ def self.union(name_or_klass = nil, **opts, &block)
470
+ define_embedded_type(name_or_klass, LibBin::Union,
471
+ "union requires a block or a LibBin::Union subclass", false, **opts, &block)
195
472
  end
196
473
 
197
474
  end
198
-
199
475
  end