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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +46 -0
- data/README.md +454 -0
- data/ext/libbin/data_types.c +1055 -284
- data/ext/libbin/data_types.h +32 -1
- data/ext/libbin/extconf.rb +15 -0
- data/ext/libbin/half.c +110 -65
- data/ext/libbin/half.h +2 -0
- data/ext/libbin/libbin_c.c +2066 -420
- data/ext/libbin/libbin_c.h +48 -1
- data/ext/libbin/libbin_io.h +506 -0
- data/ext/libbin/pghalf.c +107 -228
- data/ext/libbin/pghalf.h +2 -0
- data/lib/libbin/bitfield.rb +426 -0
- data/lib/libbin/data_shape.rb +387 -0
- data/lib/libbin/data_types.rb +264 -511
- data/lib/libbin/enum.rb +159 -0
- data/lib/libbin/union.rb +314 -0
- data/lib/libbin/utf16.rb +183 -0
- data/lib/libbin/version.rb +4 -0
- data/lib/libbin.rb +165 -14
- data/libbin.gemspec +23 -4
- metadata +46 -5
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 0ed7d92fad84a73655e2528c38031b9db4d5d1a935b59a3597bb1a1b69886497
|
|
4
|
+
data.tar.gz: 13faede48936779aafbc90216aa60258837963b537991f413b5f5acb749db7dc
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 02a2fdf4e9a20c85a02dcd7a67c5fd917fb2a2b7812bd98a0c550dff19fcfafa3ad1ba8fe7cf46d895a0197b464ab6f486c695aebb6dffa9994469bc7f5349f0
|
|
7
|
+
data.tar.gz: 3a8d70d5c3d437f920b995071c4398b8649cc9a5d972e9d6480aba04cca92b998ae3b24db59f1c623c8a6852f7c27745add5348e4a036e7fbe7a0c25a6c3889f
|
data/CHANGELOG.md
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## [2.1.0] - 2026-12-05
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
- **DSL & reverse-engineering ergonomics**:
|
|
12
|
+
- Added `LibBin::Union` and inline `union` DSL (named and anonymous, with C11-style `struct` support).
|
|
13
|
+
- Added inline `Structure.struct` and nameless `field` / `struct` / `union` embedding with promoted member accessors.
|
|
14
|
+
- Added tagged dispatch via `Structure.choice` with `Symbol`/`String`/`Proc` tags, value or `===` matchers (`Range`, etc.), `default:`, and `align:`.
|
|
15
|
+
- Added layout directives `skip` (with configurable `fill:` byte), `align_to` / `pad_to`, and fixed-record `stride`.
|
|
16
|
+
- Added configurable `null_offset:` sentinel (default `0`, supporting `nil`/`false` or custom sentinels such as `-1`).
|
|
17
|
+
- Upgraded `Bitfield` with `bit_order: :msb`, per-field `:bool` (and `?` predicates), and per-field `signed:` overrides.
|
|
18
|
+
- Added `zstring`, `string(..., trim: true)`, and `UTF16` / `UTF16_LE` / `UTF16_BE` (plus `Raw` variants).
|
|
19
|
+
- Added non-seekable / streaming IO support (`IO.pipe`, `Zlib::GzipReader` / `GzipWriter`, duck-typed streams).
|
|
20
|
+
- Added `DataShape#leaves`, `DataShape#gaps`, `DataShape#overlaps`, and `DataShape#to_table` layout inspection helpers.
|
|
21
|
+
- **Performance fast paths**:
|
|
22
|
+
- Direct C buffer fast paths for `String`, `StringIO`, and `IO::Buffer`, plus zero-copy direct pack/swap on large scalar vectors (`> 256` bytes).
|
|
23
|
+
- Cached override bitflags and direct scalar / nested `Structure` C dispatch without per-field Ruby method calls, with hoisted scalar-leaf vector loops and output buffer pre-sizing.
|
|
24
|
+
- Compiled straight-line encode/decode/initializer fast paths for `Bitfield` subclasses.
|
|
25
|
+
- **Structured errors & modern Ruby hygiene**:
|
|
26
|
+
- Added `LibBin::Error < RuntimeError` and subclasses `LibBin::EOFError`, `LibBin::ValidationError`, and `LibBin::AlignmentError` carrying `structure`, `field`, `offset`, and `index`.
|
|
27
|
+
- Added GC compaction support (`rb_gc_mark_movable` and `dcompact` on `Field` and `Structure`).
|
|
28
|
+
- Switched `LibBin.big` and `LibBin.output` to Fiber-local storage and added scoped `LibBin.with_endian` / `LibBin.with_output` helpers.
|
|
29
|
+
- Marked the C extension `rb_ext_ractor_safe(true)` with Ractor-shareable `Field`, `Enum`, `Bitfield`, and per-Ractor structure flag caching.
|
|
30
|
+
- **Packaging & CI**:
|
|
31
|
+
- Added `LibBin::VERSION`, `.yardopts`, `Rakefile`, and GitHub Actions CI covering Ruby `3.1`–`4.0` across Linux, macOS, and Windows.
|
|
32
|
+
|
|
33
|
+
### Changed
|
|
34
|
+
- Evaluated `Field` string expressions in an isolated binding (`Struct`/`Structure` method-lookup race and local-variable shadowing elimination).
|
|
35
|
+
- `cField#initialize` and `Structure#__decode_seek_offset` now use fixed C arity (`11` and `4` arguments).
|
|
36
|
+
- Modularized `lib/libbin/data_types.rb` into focused files (`data_shape.rb`, `utf16.rb`, `enum.rb`, `bitfield.rb`, `union.rb`).
|
|
37
|
+
- Updated minimum supported Ruby version in `libbin.gemspec` to `>= 3.1.0`.
|
|
38
|
+
|
|
39
|
+
### Fixed
|
|
40
|
+
- Fixed IEEE-754 half-precision and PlatinumGames half (`pghalf`) rounding and shift undefined behavior in C conversions.
|
|
41
|
+
- Evaluated field `condition:` before performing `offset:` / `align:` stream seeks.
|
|
42
|
+
- Fixed `Structure.size` when `length` is given, `Int8`/`UInt8` range checking, `Bitfield` signed/remainder handling, `Structure.inherited` state copying, and `DataRange` shape compaction.
|
|
43
|
+
|
|
44
|
+
## [2.0.0]
|
|
45
|
+
|
|
46
|
+
- Initial Ruby 2.x/3.x release with C extension (`libbin_c`) supporting declarative binary `Structure`, `Enum`, `Bitfield`, `DataShape`, `Half`, and `PGHalf`.
|
data/README.md
ADDED
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
# libbin
|
|
2
|
+
Read, write and convert Binary data in Ruby.
|
|
3
|
+
|
|
4
|
+
Detailed documentation can be found here:
|
|
5
|
+
https://kerilk.github.io/libbin/
|
|
6
|
+
|
|
7
|
+
## Guiding Principles
|
|
8
|
+
|
|
9
|
+
The goal of libbin is to provide a declarative way to describe binary files
|
|
10
|
+
formats. But, as this declarative approach is not always feasible or efficient,
|
|
11
|
+
it also provides more procedural approaches through a series of hooks that can
|
|
12
|
+
be used to override the behavior of the library.
|
|
13
|
+
|
|
14
|
+
## Example
|
|
15
|
+
|
|
16
|
+
In order to showcase usages of the library, a real life example is taken. This
|
|
17
|
+
examples reads motion files from recent PlatinumGames games (Nier Automata,
|
|
18
|
+
Bayonnetta2, ...). The format description can be found here:
|
|
19
|
+
https://github.com/Kerilk/bayonetta_tools/wiki/Motion-Formats-(mot-files)#nier-automata-and-transformers-devastation
|
|
20
|
+
|
|
21
|
+
```ruby
|
|
22
|
+
require 'libbin'
|
|
23
|
+
|
|
24
|
+
# The file is seen as big structure. Sub structures will be declared inside.
|
|
25
|
+
# contrary to what is done in the real implementation, the order of the
|
|
26
|
+
# declarations will be shown in the order they are the most interesting.
|
|
27
|
+
class MOT2File < LibBin::Structure
|
|
28
|
+
|
|
29
|
+
# The file header.
|
|
30
|
+
class Header < LibBin::Structure
|
|
31
|
+
# First field if a 4 character identifier string that is expected to be "mot\x00"
|
|
32
|
+
string :id, 4, expect: "mot\x00".b
|
|
33
|
+
uint32 :version
|
|
34
|
+
uint16 :flags
|
|
35
|
+
uint16 :frame_count
|
|
36
|
+
uint32 :offset_records
|
|
37
|
+
uint32 :num_records
|
|
38
|
+
int8 :u_a, length: 4
|
|
39
|
+
string :name, 16
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
# Register the header into our file structure
|
|
43
|
+
field :header, Header
|
|
44
|
+
|
|
45
|
+
# The animation records corresponding to the different animation tracks affected by
|
|
46
|
+
# the animation
|
|
47
|
+
class Record < LibBin::Structure
|
|
48
|
+
int16 :bone_index
|
|
49
|
+
int8 :animation_track
|
|
50
|
+
int8 :format
|
|
51
|
+
int16 :num_keys
|
|
52
|
+
# field is aligned on its size byte boundary
|
|
53
|
+
uint32 :offset, align: true
|
|
54
|
+
|
|
55
|
+
# Custom Ruby accessors can reinterpret a field (or declare an overlaid `union`):
|
|
56
|
+
def value
|
|
57
|
+
[offset].pack("L").unpack("F").first
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def value=(v)
|
|
61
|
+
self.offset = [v].pack("F").unpack("L").first
|
|
62
|
+
v
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# the size of this structure is known (Some structure's size can only be known
|
|
66
|
+
# at runtime.
|
|
67
|
+
def self.size(*args)
|
|
68
|
+
12
|
|
69
|
+
end
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
# Register the records field.
|
|
73
|
+
# The required count and offset are contained in the header.
|
|
74
|
+
# Here we showcase two different ways to express those constraints,
|
|
75
|
+
# using a string representing the path, or a proc accessing the
|
|
76
|
+
# class instance members. Accessing and setting members is done
|
|
77
|
+
# through accessors with the same name as the field.
|
|
78
|
+
# There is an additional dummy record at he end of the list.
|
|
79
|
+
field :records, Record, count: 'header\num_records + 1', offset: proc { header.offset_records }
|
|
80
|
+
|
|
81
|
+
# The format defines many way to encode the animations tracks, with
|
|
82
|
+
# incresing levels of compression, and many use interpolation with
|
|
83
|
+
# cubic Hermit splines. Unless the animation track is constant
|
|
84
|
+
# (format 0 (or -1 for dummy) in the record)
|
|
85
|
+
|
|
86
|
+
# Format 1: 1 float value per key
|
|
87
|
+
# value[frame] = keys[frame]
|
|
88
|
+
class Format1 < LibBin::Structure
|
|
89
|
+
# The number of keys is defined in the corresponding record.
|
|
90
|
+
# Our rank in the repetition gives the index in the record vector.
|
|
91
|
+
float :keys, count: proc { __parent.records[__index].num_keys }
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
# Format 2: quantized values using a 16 bit integer mutiplier
|
|
95
|
+
# value[frame] = p + key[frame] * dp
|
|
96
|
+
class Format2 < LibBin::Structure
|
|
97
|
+
float :p
|
|
98
|
+
float :dp
|
|
99
|
+
uint16 :keys, count: '..\records[__index]\num_keys'
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
# Format 3: quantized values using sepecial half floats.
|
|
103
|
+
# value[frame] = p + key[frame] * dp
|
|
104
|
+
class Format3 < LibBin::Structure
|
|
105
|
+
pghalf :p
|
|
106
|
+
pghalf :dp
|
|
107
|
+
uint16 :keys, count: '..\records[__index]\num_keys'
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
# Format 4: Cubic hermit splines.
|
|
111
|
+
class Format4 < LibBin::Structure
|
|
112
|
+
class Key < LibBin::Structure
|
|
113
|
+
uint16 :index
|
|
114
|
+
uint16 :padding #Could use align on the next field as well
|
|
115
|
+
float :p
|
|
116
|
+
float :m0
|
|
117
|
+
float :m1
|
|
118
|
+
end
|
|
119
|
+
field :keys, Key, count: '..\records[__index]\num_keys'
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
# Format 5: Cubic hermit splines with quantization
|
|
123
|
+
class Format5 < LibBin::Structure
|
|
124
|
+
class Key < LibBin::Structure
|
|
125
|
+
uint16 :index
|
|
126
|
+
uint16 :cp
|
|
127
|
+
uint16 :cm0
|
|
128
|
+
uint16 :cm1
|
|
129
|
+
end
|
|
130
|
+
float :p
|
|
131
|
+
float :dp
|
|
132
|
+
float :m0
|
|
133
|
+
float :dm0
|
|
134
|
+
float :m1
|
|
135
|
+
float :dm1
|
|
136
|
+
field :keys, Key, count: '..\records[__index]\num_keys'
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
# Format 6: Cubic hermit spline with quantization and
|
|
140
|
+
# special half floats
|
|
141
|
+
class Format6 < LibBin::Structure
|
|
142
|
+
class Key < LibBin::Structure
|
|
143
|
+
uint8 :index
|
|
144
|
+
uint8 :cp
|
|
145
|
+
uint8 :cm0
|
|
146
|
+
uint8 :cm1
|
|
147
|
+
end
|
|
148
|
+
pghalf :p
|
|
149
|
+
pghalf :dp
|
|
150
|
+
pghalf :m0
|
|
151
|
+
pghalf :dm0
|
|
152
|
+
pghalf :m1
|
|
153
|
+
pghalf :dm1
|
|
154
|
+
register_field :keys, Key, count: '..\records[__index]\num_keys'
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
# Format 7: same as 6 with relative indices
|
|
158
|
+
# Structure is exactly the same
|
|
159
|
+
class Format7 < LibBin::Structure
|
|
160
|
+
class Key < LibBin::Structure
|
|
161
|
+
uint8 :index
|
|
162
|
+
uint8 :cp
|
|
163
|
+
uint8 :cm0
|
|
164
|
+
uint8 :cm1
|
|
165
|
+
end
|
|
166
|
+
pghalf :p
|
|
167
|
+
pghalf :dp
|
|
168
|
+
pghalf :m0
|
|
169
|
+
pghalf :dm0
|
|
170
|
+
pghalf :m1
|
|
171
|
+
pghalf :dm1
|
|
172
|
+
register_field :keys, Key, count: '..\records[__index]\num_keys'
|
|
173
|
+
end
|
|
174
|
+
|
|
175
|
+
# Format 8: same as 6 but with a bigger index. This index is always store in big endian fashion
|
|
176
|
+
class Format8 < LibBin::Structure
|
|
177
|
+
class Key < LibBin::Structure
|
|
178
|
+
uint16_be :index
|
|
179
|
+
uint8 :cp
|
|
180
|
+
uint8 :cm0
|
|
181
|
+
uint8 :cm1
|
|
182
|
+
end
|
|
183
|
+
pghalf :p
|
|
184
|
+
pghalf :dp
|
|
185
|
+
pghalf :m0
|
|
186
|
+
pghalf :dm0
|
|
187
|
+
pghalf :m1
|
|
188
|
+
pghalf :dm1
|
|
189
|
+
register_field :keys, Key, count: '..\records[__index]\num_keys'
|
|
190
|
+
end
|
|
191
|
+
|
|
192
|
+
FORMATS = [nil, Format1, Format2, Format3, Format4, Format5, Format6, Format7, Format8]
|
|
193
|
+
def format(i)
|
|
194
|
+
FORMATS[i]
|
|
195
|
+
end
|
|
196
|
+
|
|
197
|
+
# register the tracks, they use relative offsets to the record position in the file
|
|
198
|
+
# note that the type is dynamic and depends on the recod content, so we use the
|
|
199
|
+
# sequence flag to tell libbin that the type and offset needs to be evaluated for
|
|
200
|
+
# each repetition
|
|
201
|
+
field :tracks, proc { format(records[__iterator].format) }, count: 'header\num_records',
|
|
202
|
+
sequence: true, condition: proc { records[__iterator].format != 0 && records[__iterator].format != -1 },
|
|
203
|
+
offset: proc { header.offset_records + Record.size * __iterator + records[__iterator].offset }
|
|
204
|
+
end
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
## Loading, Dumping, and Converting
|
|
208
|
+
|
|
209
|
+
Once a structure is defined, loading it is quite straight forward:
|
|
210
|
+
```ruby
|
|
211
|
+
require 'stringio'
|
|
212
|
+
|
|
213
|
+
# open a file in binary mode
|
|
214
|
+
File.open(File.join("test", "binary", "motion_be.bin"), "rb") do |f|
|
|
215
|
+
# Load a big endian motion file.
|
|
216
|
+
mot = MOT2File.load(f, true)
|
|
217
|
+
# print the total number of keys in tracks:
|
|
218
|
+
puts mot.records.collect(&:num_keys).reduce(:+)
|
|
219
|
+
# write the file in little endian format
|
|
220
|
+
str = StringIO.new.binmode
|
|
221
|
+
MOT2File.dump(mot, str, false) # or mot.__dump(str, false)
|
|
222
|
+
# compare the output to the reference file
|
|
223
|
+
File.open(File.join("test", "binary", "motion_le.bin"), "rb") do |g|
|
|
224
|
+
raise "Error!" unless str.string == g.read
|
|
225
|
+
end
|
|
226
|
+
# modifiying values is easy...
|
|
227
|
+
mot.header.num_records = 1
|
|
228
|
+
# ...but coherency must be maintained,
|
|
229
|
+
# so usually you will need some helper function in you classes
|
|
230
|
+
# to recompute the offsets and counts.
|
|
231
|
+
|
|
232
|
+
# You can also create new instances of those classes and
|
|
233
|
+
# Initialize the members yourself (or create an initialize
|
|
234
|
+
# method to do that for you)
|
|
235
|
+
header = MOT2File::Header.new
|
|
236
|
+
header.id = "mot\x00".b
|
|
237
|
+
# etc...
|
|
238
|
+
|
|
239
|
+
# The tests contain more examples, or the bayonetta_tools, that
|
|
240
|
+
# are mainly written using LibBin
|
|
241
|
+
end
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
## DSL & Reverse-Engineering Features
|
|
245
|
+
|
|
246
|
+
### Unions (`union` and `LibBin::Union`)
|
|
247
|
+
|
|
248
|
+
Use `union` for overlaid fields sharing the same bytes (replacing manual `pack`/`unpack` getters and setters):
|
|
249
|
+
|
|
250
|
+
```ruby
|
|
251
|
+
# Anonymous inline union — member accessors (offset, value) live directly on Record:
|
|
252
|
+
class Record < LibBin::Structure
|
|
253
|
+
int16 :bone_index
|
|
254
|
+
int8 :animation_track
|
|
255
|
+
int8 :format
|
|
256
|
+
int16 :num_keys
|
|
257
|
+
union align: 4 do
|
|
258
|
+
uint32 :offset
|
|
259
|
+
float :value
|
|
260
|
+
end
|
|
261
|
+
end
|
|
262
|
+
|
|
263
|
+
rec = Record.new
|
|
264
|
+
rec.value = 1.0
|
|
265
|
+
rec.offset # => 0x3f800000
|
|
266
|
+
Record.new.__size # => 12
|
|
267
|
+
|
|
268
|
+
# Or define a named/standalone union when you want an explicit field or reusable type:
|
|
269
|
+
class Variant < LibBin::Union
|
|
270
|
+
uint32 :as_int
|
|
271
|
+
float :as_float
|
|
272
|
+
uint8 :as_bytes, length: 4
|
|
273
|
+
end
|
|
274
|
+
|
|
275
|
+
class Entry < LibBin::Structure
|
|
276
|
+
union :payload do
|
|
277
|
+
uint32 :raw
|
|
278
|
+
float :scalar
|
|
279
|
+
end
|
|
280
|
+
field :extra, Variant
|
|
281
|
+
end
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
### Inline & Anonymous Structures (`struct` and nameless `field`)
|
|
285
|
+
|
|
286
|
+
Use `struct` to define inline nested structures (named or anonymous) — including inside `union` for multi-field union branches — and use nameless `field` (or `struct`/`union`) to embed shared definitions without an extra accessor indirection:
|
|
287
|
+
|
|
288
|
+
```ruby
|
|
289
|
+
class CommonHeader < LibBin::Structure
|
|
290
|
+
uint16 :magic
|
|
291
|
+
uint16 :version
|
|
292
|
+
end
|
|
293
|
+
|
|
294
|
+
# Anonymous struct inside a Union (C11 style)
|
|
295
|
+
class PointerPayload < LibBin::Union
|
|
296
|
+
struct do
|
|
297
|
+
uint32_le :pmclass
|
|
298
|
+
uint16_le :pmenum
|
|
299
|
+
end
|
|
300
|
+
uint32_le :btype
|
|
301
|
+
end
|
|
302
|
+
|
|
303
|
+
# Factor shared layouts via nameless embedding, group optional fields anonymously,
|
|
304
|
+
# or declare named inline sub-structs:
|
|
305
|
+
class Packet < LibBin::Structure
|
|
306
|
+
field CommonHeader # promotes :magic and :version directly onto Packet
|
|
307
|
+
struct :meta do # named inline sub-structure (packet.meta.flags)
|
|
308
|
+
uint32 :flags
|
|
309
|
+
end
|
|
310
|
+
struct condition: 'version >= 2' do # conditional group with promoted accessors
|
|
311
|
+
uint32 :extra_a
|
|
312
|
+
uint32 :extra_b
|
|
313
|
+
end
|
|
314
|
+
field PointerPayload # promotes :pmclass, :pmenum, :btype onto Packet
|
|
315
|
+
end
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
### Tagged Dispatch (`choice`)
|
|
319
|
+
|
|
320
|
+
Use `choice` to select a field's type from a tag field, expression, or `Proc`:
|
|
321
|
+
|
|
322
|
+
```ruby
|
|
323
|
+
class SubBlock < LibBin::Structure
|
|
324
|
+
uint32 :id
|
|
325
|
+
uint32 :value
|
|
326
|
+
end
|
|
327
|
+
|
|
328
|
+
class Chunk < LibBin::Structure
|
|
329
|
+
uint8 :kind
|
|
330
|
+
choice :body, :kind, {
|
|
331
|
+
0 => nil, # absent (also skips offset seek if offset: is given)
|
|
332
|
+
1 => :uint16, # built-in type shorthand symbol
|
|
333
|
+
2..3 => SubBlock, # Range / === matcher
|
|
334
|
+
}, default: :float, align: true
|
|
335
|
+
end
|
|
336
|
+
```
|
|
337
|
+
|
|
338
|
+
Supported type shorthands in `choice` and `Structure.resolve_type`: `:int8`, `:uint8`, `:int16`/`_le`/`_be`, `:uint16`/`_le`/`_be`, `:int32`/`_le`/`_be`, `:uint32`/`_le`/`_be`, `:int64`/`_le`/`_be`, `:uint64`/`_le`/`_be`, `:float`/`_le`/`_be`, `:double`/`_le`/`_be`, `:half`/`_le`/`_be`, `:pghalf`/`_le`/`_be`, `:string`, `:zstring`, `:utf16`, `:utf16_le`, `:utf16_be`.
|
|
339
|
+
|
|
340
|
+
### Layout Directives (`skip`, `align_to` / `pad_to`, `stride`)
|
|
341
|
+
|
|
342
|
+
Declare padding or fixed record sizes without throwaway fields:
|
|
343
|
+
|
|
344
|
+
```ruby
|
|
345
|
+
class PaddedEntry < LibBin::Structure
|
|
346
|
+
uint8 :tag
|
|
347
|
+
skip 3, fill: 0xff # skip 3 bytes on load (0xff-filled on dump, preserved on convert)
|
|
348
|
+
uint16 :code
|
|
349
|
+
pad_to 8 # align current offset up to an 8-byte boundary (alias for align_to)
|
|
350
|
+
uint32 :value
|
|
351
|
+
stride 16 # enforce fixed 16-byte record size (trailing bytes skipped/zero-padded)
|
|
352
|
+
end
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
### Configurable Null-Offset Sentinel (`null_offset:`)
|
|
356
|
+
|
|
357
|
+
By default `offset:` treats `0` as an absent/null pointer. Override it with `null_offset:` when `0` is a valid offset or when a format uses another sentinel such as `-1` or `0xffffffff`:
|
|
358
|
+
|
|
359
|
+
```ruby
|
|
360
|
+
class Table < LibBin::Structure
|
|
361
|
+
uint32 :first_entry_offset
|
|
362
|
+
int32 :optional_offset
|
|
363
|
+
uint32 :first_entry, offset: 'first_entry_offset', null_offset: nil # offset 0 is valid
|
|
364
|
+
uint32 :optional, offset: 'optional_offset', null_offset: -1 # -1 means absent
|
|
365
|
+
end
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
### Bitfield Upgrades (`bit_order: :msb`, per-field `signed:`, `:bool`)
|
|
369
|
+
|
|
370
|
+
Bitfields support MSB-first console/PowerPC packing, per-field signedness, and 1-bit booleans (with `?` predicate helpers):
|
|
371
|
+
|
|
372
|
+
```ruby
|
|
373
|
+
class PackedVertexFlags < LibBin::Structure
|
|
374
|
+
# DEC3N-style 10/10/10 signed normal with 2-bit flag MSB-first
|
|
375
|
+
bitfield :normal_bits, {
|
|
376
|
+
pad: 2,
|
|
377
|
+
z: { bits: 10, signed: true },
|
|
378
|
+
y: { bits: 10, signed: true },
|
|
379
|
+
x: { bits: 10, signed: true }
|
|
380
|
+
}, size: 32, bit_order: :msb
|
|
381
|
+
|
|
382
|
+
# Per-field booleans and mixed signed/unsigned bit slices
|
|
383
|
+
bitfield :flags, {
|
|
384
|
+
visible: :bool,
|
|
385
|
+
lod: 3,
|
|
386
|
+
bias: { bits: 4, signed: true },
|
|
387
|
+
locked: { type: :bool }
|
|
388
|
+
}, size: 16
|
|
389
|
+
end
|
|
390
|
+
# pkt.flags.visible? => true/false
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
### Strings (`zstring`, `trim: true`, `utf16` / `utf16_le` / `utf16_be`)
|
|
394
|
+
|
|
395
|
+
```ruby
|
|
396
|
+
class AssetHeader < LibBin::Structure
|
|
397
|
+
zstring :name, 16 # fixed 16-byte buffer, trimmed at first NUL (shorthand for trim: true)
|
|
398
|
+
zstring :comment # variable-length NUL-terminated string (strips trailing NUL)
|
|
399
|
+
utf16_le :title, 12 # fixed 12 code units (24 bytes), NUL-trimmed UTF-16LE <-> UTF-8
|
|
400
|
+
utf16_be :subtitle # NUL-terminated UTF-16BE <-> UTF-8
|
|
401
|
+
end
|
|
402
|
+
```
|
|
403
|
+
|
|
404
|
+
### Buffers & Non-Seekable Streams
|
|
405
|
+
|
|
406
|
+
`Structure.{load,dump,convert}` directly fast-path `String`, `StringIO`, and `IO::Buffer`, and track byte offsets across sequential non-seekable streams (`IO.pipe`, `Zlib::GzipReader`/`GzipWriter`, or minimal `read`/`write` objects) — including `align:`, `align_to`, `skip`, and `stride`:
|
|
407
|
+
|
|
408
|
+
```ruby
|
|
409
|
+
# Load directly from an ASCII-8BIT String or IO::Buffer, or dump into a String:
|
|
410
|
+
obj = AssetHeader.load(bytes, false)
|
|
411
|
+
out = "".b
|
|
412
|
+
AssetHeader.dump(obj, out, false)
|
|
413
|
+
|
|
414
|
+
# Stream sequentially through Zlib::GzipReader / IO.pipe:
|
|
415
|
+
Zlib::GzipReader.open("packet.bin.gz") { |gz| PaddedEntry.load(gz, false) }
|
|
416
|
+
```
|
|
417
|
+
|
|
418
|
+
### Reverse-Engineering Layout Inspection (`DataShape`)
|
|
419
|
+
|
|
420
|
+
Inspect field spans, unmapped byte gaps, and overlapping fields directly from `__shape`:
|
|
421
|
+
|
|
422
|
+
```ruby
|
|
423
|
+
shape = obj.__shape
|
|
424
|
+
shape.leaves(include_padding: true) # flat list of DataShape::Span(path, range, padding)
|
|
425
|
+
shape.gaps(total_size: 32) # uncovered byte Ranges (respecting stride/padding)
|
|
426
|
+
shape.overlaps # DataShape::Overlap ranges for colliding fields
|
|
427
|
+
|
|
428
|
+
puts shape.to_table(max_depth: 2, collapse_arrays: true)
|
|
429
|
+
# Start End Size Field Notes
|
|
430
|
+
# ------ ------ ---- ------- -----
|
|
431
|
+
# 0x0000 0x0000 1 tag
|
|
432
|
+
# 0x0001 0x0003 3 __pad_1 <PAD>
|
|
433
|
+
# 0x0004 0x0005 2 code
|
|
434
|
+
# 0x0006 0x0007 2 __pad_3 <PAD>
|
|
435
|
+
# 0x0008 0x000b 4 value
|
|
436
|
+
# 0x000c 0x000f 4 <GAP>
|
|
437
|
+
# Total: 16 bytes | Gaps: 1 (4 bytes) | Overlaps: 0
|
|
438
|
+
```
|
|
439
|
+
|
|
440
|
+
### Structured Exceptions & Concurrency (`LibBin::Error`, Fiber / Ractor Safety)
|
|
441
|
+
|
|
442
|
+
`LibBin` raises structured subclasses of `LibBin::Error < RuntimeError` (`LibBin::EOFError`, `LibBin::ValidationError`, `LibBin::AlignmentError`) carrying `#structure`, `#field`, `#offset`, and `#index` of the innermost failing frame. `LibBin.big` and `LibBin.output` are Fiber-local (scoped cleanly via `LibBin.with_endian` / `LibBin.with_output`), and the C extension supports Ruby GC compaction and parallel `Ractor` execution:
|
|
443
|
+
|
|
444
|
+
```ruby
|
|
445
|
+
LibBin.with_endian(false) do
|
|
446
|
+
LibBin.with_output(nil) do # silence frame trace output if handling programmatically
|
|
447
|
+
begin
|
|
448
|
+
Chunk.load("\x01\x00".b)
|
|
449
|
+
rescue LibBin::EOFError => e
|
|
450
|
+
warn "#{e.structure}##{e.field} at offset=#{e.offset} (index=#{e.index.inspect}): #{e.message}"
|
|
451
|
+
end
|
|
452
|
+
end
|
|
453
|
+
end
|
|
454
|
+
```
|