libbin 2.0.0 → 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,97 +1,7 @@
1
- module LibBin
2
-
3
- # Refinement to Range allowing reducing ranges through the + operator
4
- module RangeRefinement
5
- refine Range do
6
- # Union of two ranges
7
- # @return [Range]
8
- def +(other)
9
- return other.dup unless min
10
- return self.dup unless other.min
11
- Range::new(min <= other.min ? min : other.min,
12
- max >= other.max ? max : other.max)
13
- end
14
- end
15
- end
16
-
17
- # Classs that can be used to get the shape of a {Structure} or of a {Structure::Scalar}.
18
- class DataRange
19
- using RangeRefinement
20
- attr_reader :range
21
-
22
- # @overload initialize(min, max)
23
- # Create a new shape starting and +min+ and ending at max.
24
- # This shape has no members.
25
- # @param min [Integer] start of the shape
26
- # @param max [Integer] end of the shape
27
- # @return [DataShape] a new DataShape
28
- # @overload initialize(members)
29
- # Creates a new shape by reducing the shape of it's memebers.
30
- # @param members [DataShape] the members composing the shape
31
- # @return [DataShape] a new DataShape
32
- def initialize(*args)
33
- if args.length == 2
34
- @range = Range::new(args[0], args[1])
35
- else
36
- if args[0].kind_of?(Hash)
37
- @range = args[0].values.compact.collect(&:range).reduce(:+)
38
- else
39
- @range = args[0].compact.collect(&:range).reduce(:+)
40
- end
41
- end
42
- end
1
+ require 'stringio'
2
+ require_relative 'data_shape'
43
3
 
44
- # Return the beginning of the shape
45
- # @return [Integer]
46
- def first
47
- @range.first
48
- end
49
-
50
- # Return the end of the shape
51
- # @return [Integer]
52
- def last
53
- @range.last
54
- end
55
-
56
- # Return the size of the shape
57
- # @return [Integer]
58
- def size
59
- @range.size
60
- end
61
-
62
- end
63
-
64
- # Default class used to get the shape of a {Structure} or of a {Structure::Scalar}.
65
- # It maintains a memory of it's members
66
- class DataShape # < DataRange
67
- using RangeRefinement
68
- attr_reader :members
69
-
70
- # Add method readers for members
71
- def method_missing(m, *arg, &block)
72
- return @members[m] if @members && @members[m]
73
- super
74
- end
75
-
76
- # @overload initialize(min, max)
77
- # Create a new shape starting and +min+ and ending at max.
78
- # This shape has no members.
79
- # @param min [Integer] start of the shape
80
- # @param max [Integer] end of the shape
81
- # @return [DataShape] a new DataShape
82
- # @overload initialize(members)
83
- # Creates a new shape by reducing the shape of it's memeber.
84
- # Members can be accessed through {members}.
85
- # @param members [DataShape] the members composing the shape
86
- # @return [DataShape] a new DataShape
87
- def initialize(*args)
88
- if args.length == 1
89
- @members = args[0]
90
- end
91
- super
92
- end
93
-
94
- end
4
+ module LibBin
95
5
 
96
6
  # @abstract This class is used to describe a binary data structure
97
7
  # composed of different fields.
@@ -99,7 +9,6 @@ module LibBin
99
9
 
100
10
  # @!parse
101
11
  # # Field class that is instantiated to describe a structure field.
102
- # # Instances are immutable.
103
12
  # class Field
104
13
  # attr_reader :name
105
14
  # attr_reader :type
@@ -119,62 +28,122 @@ module LibBin
119
28
  # # @return [Boolean] field is a sequence
120
29
  # end
121
30
 
122
- # Define a new field in the structure
123
- # @param name [Symbol, String] the name of the field.
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
44
+ end
45
+ align
46
+ end
47
+ private_class_method :resolve_align
48
+
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
72
+
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
86
+ end
87
+ private_class_method :promote_embedded_accessors
88
+
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
124
96
  # @param type [Class, String, Proc] the type of the field, as a Class, or
125
97
  # as a String or Proc that will be evaluated in the context of the
126
98
  # {Structure} instance.
127
99
  # @param length [Integer, String, Proc] if given, consider the field a
128
- # vector of the type. The length is either a constant Integer of a
129
- # String or Proc that will be evaluated in the context of the
130
- # {Structure} instance.
131
- # @param count [Integer, String, Proc] if given, consider the field is
132
- # repeated count times. The count is either a constant Integer of a
133
- # String or Proc that will be evaluated in the context of the
134
- # {Structure} instance.
135
- # @param offset [integer, String, Proc] if given, the absolute offset in
136
- # the file, or the offset from the parent position, where the field can
137
- # be found. See relative offset. The offset is either a constant
138
- # Integer of a String or Proc that will be evaluated in the context
139
- # of the {Structure} instance.
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+).
140
104
  # @param sequence [Boolean] if true, +type+, +length+, +offset+, and
141
105
  # +condition+ are evaluated for each repetition.
142
- # @param condition [String, Proc] if given, the field, or repetition of the
143
- # field can be conditionally present. The condition will be evaluated in
144
- # the context of the {Structure} instance.
145
- # @param relative_offset [Boolean] consider the +offset+ relative to the
146
- # field +parent+.
147
- # @param align [Boolean,Integer] if given, align the field. If given as an
148
- # Integer it must be a power of 2. Else the field is aligned to the
149
- # field's type preferred alignment.
150
- # @param expect [Proc, Object] if given, the field value must validate or
151
- # an eexception is raised. If a proc the proc resulted must be truthy. If
152
- # not, the object will be tested for equality.
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+).
153
111
  # @return self
154
- def self.field(name, type, length: nil, count: nil, offset: nil,
112
+ def self.field(name, type = FIELD_TYPE_UNSET, length: nil, count: nil, offset: nil,
155
113
  sequence: false, condition: nil, relative_offset: false,
156
- align: false, expect: nil)
157
- if type.respond_to?(:always_align) && type.always_align
158
- al = type.align
159
- if align.kind_of?(Integer)
160
- align = align >= al ? align : al
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
161
119
  else
162
- align = al
120
+ raise ArgumentError, "wrong number of arguments (given 1, expected 2)"
163
121
  end
164
122
  end
165
- if align == true
166
- # Automatic alignment not supported for dynamic types
167
- if type.respond_to?(:align)
168
- align = type.align
169
- else
170
- raise "alignment is unsupported for dynamic types"
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"
171
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
172
144
  else
173
- raise "alignement must be a power of 2" if align && (align - 1) & align != 0
145
+ Structure.__bump_override_gen
174
146
  end
175
- @fields.push(Field::new(name, type, length, count, offset, sequence,
176
- condition, relative_offset, align, expect))
177
- attr_accessor name
178
147
  self
179
148
  end
180
149
 
@@ -263,19 +232,11 @@ module LibBin
263
232
  # Create a new field of type {$1} and name +name+. See {field} for options.
264
233
  # @return self
265
234
  #
266
- def self.define_scalar_constructor(klassname, name, mapped_type, description)
267
- eval <<EOF
268
- def self.#{name}(name, length: nil, count: nil, offset: nil, sequence: false, condition: nil, relative_offset: false, align: false, expect: nil)
269
- if align == true
270
- align = #{klassname}.align
271
- else
272
- raise "alignement must be a power of 2" if align && (align - 1) & align != 0
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)
273
239
  end
274
- @fields.push(Field::new(name, #{klassname}, length, count, offset, sequence, condition, relative_offset, align, expect))
275
- attr_accessor name
276
- self
277
- end
278
- EOF
279
240
  end
280
241
  private_class_method :define_scalar_constructor
281
242
 
@@ -288,13 +249,13 @@ EOF
288
249
  define_scalar_constructor "UInt16", :uint16, :uint16_t, "An unsigned 16 bit integer"
289
250
  define_scalar_constructor "UInt16_LE", :uint16_le, :uint16_t, "An unsigned little endian 16 bit integer"
290
251
  define_scalar_constructor "UInt16_BE", :uint16_be, :uint16_t, "An unsigned big endian 16 bit integer"
291
- define_scalar_constructor "Int32", :int32, :int32_t, "A signed little endian 32 bit integer"
252
+ define_scalar_constructor "Int32", :int32, :int32_t, "A signed 32 bit integer"
292
253
  define_scalar_constructor "Int32_LE", :int32_le, :int32_t, "A signed little endian 32 bit integer"
293
254
  define_scalar_constructor "Int32_BE", :int32_be, :int32_t, "A signed big endian 32 bit integer"
294
255
  define_scalar_constructor "UInt32", :uint32, :uint32_t, "An unsigned 32 bit integer"
295
256
  define_scalar_constructor "UInt32_LE", :uint32_le, :uint32_t, "An unsigned little endian 32 bit integer"
296
257
  define_scalar_constructor "UInt32_BE", :uint32_be, :uint32_t, "An unsigned big endian 32 bit integer"
297
- define_scalar_constructor "Int64", :int64, :int64_t, "A signed little endian 64 bit integer"
258
+ define_scalar_constructor "Int64", :int64, :int64_t, "A signed 64 bit integer"
298
259
  define_scalar_constructor "Int64_LE", :int64_le, :int64_t, "A signed little endian 64 bit integer"
299
260
  define_scalar_constructor "Int64_BE", :int64_be, :int64_t, "A signed big endian 64 bit integer"
300
261
  define_scalar_constructor "UInt64", :uint64, :uint64_t, "An unsigned 64 bit integer"
@@ -318,405 +279,197 @@ EOF
318
279
  # class Str < Scalar
319
280
  # end
320
281
 
321
- # Create a new field of type {Str} and name +name+. See {field} for options.
282
+ # Create a new field of type {Str} (or {ZStr} if +trim: true+) and name +name+. See {field} for options.
322
283
  # @return self
323
- def self.string(field, length = nil, count: nil, offset: nil, sequence: false, condition: nil, relative_offset: false, align: false, expect: nil)
324
- if align == true
325
- align = Str.align
326
- else
327
- raise "alignement must be a power of 2" if align && (align - 1) & align != 0
328
- end
329
- @fields.push(Field::new(field, Str, length, count, offset, sequence, condition, relative_offset, align, expect))
330
- attr_accessor field
331
- self
284
+ def self.string(field_name, length = nil, trim: false, **opts)
285
+ self.field(field_name, trim ? ZStr : Str, length: length, **opts)
332
286
  end
333
287
 
334
- # @abstract A parent class representing an enumeration that is loading integers as symbols.
335
- # Useer should inherit this base class.
336
- class Enum
337
- class << self
338
- #get the enum map
339
- attr_reader :map
340
- # Get the underlying type
341
- attr_accessor :type
342
-
343
- # Specify the size of the underlying type
344
- def type_size=(sz)
345
- t = eval "Int#{sz}"
346
- raise "unsupported enum size #{sz}" unless t
347
- @type = t
348
- return sz
349
- end
350
- alias set_type_size type_size=
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
351
293
 
352
- # Get the underlying type size in bits
353
- def type_size
354
- @type.size
355
- end
294
+ FILL_CLASS_CACHES = { Skip => {}, AlignTo => {} }.freeze
295
+ private_constant :FILL_CLASS_CACHES
356
296
 
357
- # Set the enum map
358
- # @param m [Hash{Symbol=>Integer}] enum values
359
- def map=(m)
360
- @map_to = m.invert
361
- @map_from = @map = m
362
- end
363
- alias set_map map=
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
364
300
 
365
- # @!visibility private
366
- def inherited(subclass)
367
- subclass.instance_variable_set(:@type, Int32)
368
- end
369
- end
301
+ FILL_CLASS_CACHES[base][fill] ||= Class.new(base) { |c| c.instance_variable_set(:@fill, fill) }
302
+ end
303
+ private_class_method :fill_class_for
370
304
 
371
- # Returns the underlying type +always_align+ property
372
- def self.always_align
373
- @type.always_align
374
- end
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)
312
+ end
375
313
 
376
- # Returns the underlying type +align+ property
377
- def self.align
378
- @type.align
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"
379
321
  end
322
+ klass = Structure.send(:fill_class_for, AlignTo, fill)
323
+ self.field(nil, klass, length: alignment, condition: condition)
324
+ end
380
325
 
381
- # Forwards the call to the underlying type
382
- def self.size(value = nil, previous_offset = 0, parent = nil, index = nil, length = nil)
383
- @type.size(value, previous_offset, parent, index, length)
384
- end
326
+ class << self
327
+ alias pad_to align_to
328
+ end
385
329
 
386
- # Forwards the call to the underlying type
387
- def self.shape(value = nil, previous_offset = 0, parent = nil, index = nil, kind = DataShape, length = nil)
388
- @type.shape(value, previous_offset, parent, index, kind, length)
389
- end
330
+ end
331
+ end
390
332
 
391
- # Load a field of type {Enum} from +input+, and return it.
392
- # @param input [IO] the stream to load the field from.
393
- # @param input_big [Boolean] the endianness of +input+
394
- # @param parent [Structure] ignored.
395
- # @param index [Integer] ignored.
396
- # @param length [Integer] if given the length of the vector. Else
397
- # the length is considered to be 1.
398
- # @return [Symbol,Integer,Array<Symbol,Integer>] the Ruby
399
- # representation of the type, or the Array representation of the
400
- # vector if +length+ was specified
401
- def self.load(input, input_big = LibBin::default_big?, parent = nil, index = nil, length = nil)
402
- v = @type.load(input, input_big, parent, index, length)
403
- if length
404
- v.collect { |val|
405
- n = @map_to[val]
406
- n = val unless n
407
- n
408
- }
409
- else
410
- n = @map_to[v]
411
- n = v unless n
412
- n
413
- end
414
- end
333
+ require_relative 'utf16'
334
+ require_relative 'enum'
335
+ require_relative 'bitfield'
336
+ require_relative 'union'
415
337
 
416
- # Convert a field of class {Enum} by loading it from +input+ and
417
- # dumping it to +output+. Returns the loaded field.
418
- # @param input [IO] the stream to load the field from.
419
- # @param output [IO] the stream to dump the field to.
420
- # @param input_big [Boolean] the endianness of +input+
421
- # @param output_big [Boolean] the endianness of +output+.
422
- # @param parent [Structure] ignored.
423
- # @param index [Integer] ignored.
424
- # @param length [Integer] if given the length of the vector. Else
425
- # the length is considered to be 1.
426
- # @return [Symbol,Integer,Array<Symbol,Integer>] the Ruby representation
427
- # of the type, or the Array representation of the vector if +length+
428
- # was specified
429
- def self.convert(input, output, input_big = LibBin::default_big?, output_big = !input_big, parent = nil, index = nil, length = nil)
430
- v = @type.convert(input, output, input_big, output_big, parent, index, length)
431
- if length
432
- v.collect { |val|
433
- n = @map_to[val]
434
- n = val unless n
435
- n
436
- }
437
- else
438
- n = @map_to[v]
439
- n = v unless n
440
- n
441
- end
442
- end
338
+ module LibBin
339
+ class Structure
443
340
 
444
- # Dump a field of class {Enum} to +output+.
445
- # @param value [Numeric, Array<Numeric>] the Ruby representation
446
- # of the type, or the Array representation of the vector if
447
- # +length+ is specified.
448
- # @param output [IO] the stream to dump the field to.
449
- # @param output_big [Boolean] the endianness of +output+.
450
- # @param parent [Structure] ignored.
451
- # @param index [Integer] ignored.
452
- # @param length [Integer] if given the length of the vector. Else
453
- # the length is considered to be 1.
454
- # @return [nil]
455
- def self.dump(value, output, output_big = LibBin::default_big?, parent = nil, index = nil, length = nil)
456
- if length
457
- v = length.times.collect { |i|
458
- val = @map_from[value[i]]
459
- val = value[i] unless val
460
- val
461
- }
462
- else
463
- v = @map_from[value]
464
- v = value unless v
465
- end
466
- @type.dump(v, output, output_big, parent, index, length)
467
- end
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
360
+
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
468
366
  end
469
367
 
470
- # Create a new field of a type inheriting from {Enum} and name +name+.
471
- # See {field} for more options
472
- # @param name [Symbol,String] name of the field.
473
- # @param map [Hash{Symbol => Integer}] enum values.
474
- # @param size [Integer] size in bits of the underlying integer
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+
475
373
  # @return self
476
- def self.enum(name, map, size: 32, length: nil, count: nil, offset: nil, sequence: false, condition: nil, relative_offset: false, align: false, expect: nil)
477
- klass = Class.new(Enum) do |c|
478
- c.type_size = size
479
- c.map = map
480
- end
481
- if klass.always_align
482
- al = klass.align
483
- if align.kind_of?(Integer)
484
- align = align >= al ? align : al
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
485
384
  else
486
- align = al
487
- end
488
- end
489
- if align == true
490
- align = klass.align
491
- else
492
- raise "alignement must be a power of 2" if align && (align - 1) & align != 0
493
- end
494
- @fields.push(Field::new(name, klass, length, count, offset, sequence, condition, relative_offset, align, expect))
495
- attr_accessor name
496
- self
497
- end
498
-
499
- # @abstract A parent class that represent a bitfield that is
500
- # loading integers as an instance of itself.
501
- # User should inherit this base class.
502
- class Bitfield
503
- class << self
504
- # Bitfield's field names and number of bits
505
- attr_reader :map
506
- # Signedness of the underlying type
507
- attr_reader :signed
508
- # Underlying type
509
- attr_reader :type
510
-
511
- # Set the size and signedness of the underlying type
512
- def set_type_size(sz, signed = false)
513
- tname = "#{signed ? "" : "U"}Int#{sz}"
514
- t = eval tname
515
- raise "unsupported bitfield type #{tname}" unless t
516
- @type = t
517
- @signed = signed
518
- return sz
385
+ raise ArgumentError, "choice tag must be a Symbol, String, or Proc (got #{tag.inspect})"
519
386
  end
520
387
 
521
- # Set the underlying type
522
- def type=(type)
523
- @type = type
524
- @signed = type.name.split('::').last[0] != "U"
525
- type
526
- end
527
- alias set_type type=
528
-
529
- # Set the bitfield's field names and number of bits
530
- # Creates accessor to fields for instance of this class
531
- def map=(m)
532
- raise "map already set" if @map
533
- @map = m.each.collect { |k, v| [k, [v, k.to_sym, :"#{k}="]] }.to_h
534
- m.each_key { |k|
535
- attr_accessor k
536
- }
537
- m
538
- end
539
- alias set_map map=
540
-
541
- # @!visibility private
542
- def inherited(subclass)
543
- subclass.instance_variable_set(:@type, UInt32)
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
544
396
  end
545
397
  end
398
+ resolved_default = default.equal?(CHOICE_UNSET) ? CHOICE_UNSET : resolve_type(default)
546
399
 
547
- # Unused bits of underlying value
548
- attr_accessor :__remainder
549
-
550
- # set only the unused bits of the underlying value
551
- def __remainder=(v) # only keep relevant bits of the remainder
552
- if v != 0
553
- num_bits = self.class.type.size * 8
554
- num_used_bits = self.class.map.value.collect { |v, _, _| v }.select { |v| v > 0 }.sum(:+)
555
- if num_used_bits < num_bits
556
- v &= ((( 1 << (num_bits - num_used_bits)) - 1) << num_used_bits)
557
- else
558
- v = 0
559
- end
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}"
560
410
  end
561
- @__remainder = v
562
- end
563
-
564
- # @!visibility private
565
- def initialize
566
- @__remainder = 0
567
- end
568
-
569
- # @!visibility private
570
- def __set_value(val)
571
- base = 0
572
- self.class.map.each { |k, (v, _, s)|
573
- next if v <= 0
574
- tmp = (val >> base) & ((1 << v) - 1)
575
- val ^= tmp << base #remove bits from val
576
- tmp -= (1 << v) if self.class.signed && tmp >= (1 << (v - 1))
577
- send(s, tmp)
578
- base += v
579
- }
580
- @__remainder = val
581
- end
582
-
583
- # @!visibility private
584
- def __get_value
585
- base = 0
586
- val = 0
587
- self.class.map.each { |k, (v, g, _)|
588
- next if v <= 0
589
- val |= ((send(g) & ((1 << v) - 1)) << base)
590
- base += v
591
- }
592
- val | @__remainder
593
- end
594
-
595
- # Returns the underlying type +always_align+ property
596
- def self.always_align
597
- @type.always_align
598
411
  end
599
412
 
600
- # Returns the underlying type +align+ property
601
- def self.align
602
- @type.align
603
- end
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?)
604
416
 
605
- # Forwards the call to the underlying type
606
- def self.size(value = nil, previous_offset = 0, parent = nil, index = nil, length = nil)
607
- @type.size(value, previous_offset, parent, index, length)
608
- end
609
-
610
- # Forwards the call to the underlying type
611
- def self.shape(value = nil, previous_offset = 0, parent = nil, index = nil, kind = DataShape, length = nil)
612
- @type.shape(value, previous_offset, parent, index, kind, length)
613
- end
614
-
615
- # Load a {Bitfield} from +input+, and return it.
616
- # @param input [IO] the stream to load the field from.
617
- # @param input_big [Boolean] the endianness of +input+
618
- # @param parent [Structure] ignored.
619
- # @param index [Integer] ignored.
620
- # @param length [Integer] if given the length of the vector. Else
621
- # the length is considered to be 1.
622
- # @return [Bitfield,Array<Bitfield>] an instance of self, or an
623
- # Array if length was specified
624
- def self.load(input, input_big = LibBin::default_big?, parent = nil, index = nil, length = nil)
625
- v = @type.load(input, input_big, parent, index, length)
626
- if length
627
- v.collect { |val|
628
- bf = self.new
629
- bf.__set_value(val)
630
- bf
631
- }
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
632
425
  else
633
- bf = self.new
634
- bf.__set_value(v)
635
- bf
426
+ align
636
427
  end
637
- end
638
428
 
639
- # Convert a {Bitfield} by loading it from +input+ and
640
- # dumping it to +output+. Returns the loaded field.
641
- # @param input [IO] the stream to load the field from.
642
- # @param output [IO] the stream to dump the field to.
643
- # @param input_big [Boolean] the endianness of +input+
644
- # @param output_big [Boolean] the endianness of +output+.
645
- # @param parent [Structure] ignored.
646
- # @param index [Integer] ignored.
647
- # @param length [Integer] if given the length of the vector. Else
648
- # the length is considered to be 1.
649
- # @return [Bitfield,Array<Bitfield>] an instance of self, or an
650
- # Array if length was specified
651
- def self.convert(input, output, input_big = LibBin::default_big?, output_big = !input_big, parent = nil, index = nil, length = nil)
652
- v = @type.convert(input, output, input_big, output_big, parent, index, length)
653
- if length
654
- v.collect { |val|
655
- bf = self.new
656
- bf.__set_value(val)
657
- bf
658
- }
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
659
436
  else
660
- bf = self.new
661
- bf.__set_value(v)
662
- bf
437
+ condition
663
438
  end
664
- end
665
439
 
666
- # Dump a {Bitfield} to +output+.
667
- # @param value [Bitfield, Array<Bitfield>] the Ruby representation
668
- # of the type, or the Array representation of the vector if
669
- # +length+ is specified.
670
- # @param output [IO] the stream to dump the field to.
671
- # @param output_big [Boolean] the endianness of +output+.
672
- # @param parent [Structure] ignored.
673
- # @param index [Integer] ignored.
674
- # @param length [Integer] if given the length of the vector. Else
675
- # the length is considered to be 1.
676
- # @return [nil]
677
- def self.dump(value, output, output_big = LibBin::default_big?, parent = nil, index = nil, length = nil)
678
- v =
679
- if length
680
- length.times.collect { |i|
681
- value[i].__get_value
682
- }
683
- else
684
- value.__get_value
685
- end
686
- @type.dump(v, output, output_big, parent, index, length)
687
- end
440
+ self.field(name, proc { resolver.call(self) }, condition: combined_condition, align: resolved_align, **opts)
688
441
  end
689
442
 
690
- # Create a new field of a type inheriting from {Bitfield} and name +name+.
691
- # See {field} for more options
692
- # @param name [Symbol,String] name of the field.
693
- # @param map [Hash{Symbol => Integer}] bitfield field names and number of bits.
694
- # @param size [Integer] size in bits of the underlying integer
695
- # @param signed [Boolean] signedness of the underlying type
696
- # @return self
697
- def self.bitfield(name, map, size: 32, signed: false, length: nil, count: nil, offset: nil, sequence: false, condition: nil, relative_offset: false, align: false, expect: nil)
698
- klass = Class.new(Bitfield) do |c|
699
- c.set_type_size(size, signed)
700
- c.set_map(map)
701
- end
702
- if klass.always_align
703
- al = klass.align
704
- if align.kind_of?(Integer)
705
- align = align >= al ? align : al
706
- else
707
- align = al
708
- end
709
- end
710
- if align == true
711
- align = klass.align
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
712
451
  else
713
- raise "alignement must be a power of 2" if align && (align - 1) & align != 0
452
+ raise ArgumentError, error_msg
714
453
  end
715
- @fields.push(Field::new(name, klass, length, count, offset, sequence, condition, relative_offset, align, expect))
716
- attr_accessor name
717
- self
454
+ self.field(name, klass, **opts)
718
455
  end
456
+ private_class_method :define_embedded_type
719
457
 
720
- end
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
721
465
 
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)
472
+ end
473
+
474
+ end
722
475
  end