11class BinaryParser
2- @io : IO ?
3-
42 def load (filename : String )
5- @ io = File .open(filename)
6- load(@io .not_nil! )
3+ io = File .open(filename)
4+ load(io )
75 end
86
97 def load (io : IO )
@@ -15,17 +13,39 @@ class BinaryParser
1513 self
1614 end
1715
16+ def save (filename : String )
17+ io = File .open(filename, " w" )
18+ save(io)
19+ end
20+
21+ def save (io : IO )
22+ {% for method in @type .methods % }
23+ {% if method.name.starts_with?(" _write_" ) % }
24+ {{method.name}}(io)
25+ {% end % }
26+ {% end % }
27+ self
28+ end
29+
1830 def self.from_io (io : IO , format : IO ::ByteFormat )
1931 ins = self .new
2032 ins.load(io)
2133 end
2234
35+ def to_io (io : IO , format : IO ::ByteFormat )
36+ save(io)
37+ end
38+
2339 macro uint32 (name )
2440 property! :{{name.id}}
2541
2642 def _read_ {{name.id}}(io : IO )
2743 @{{name.id}} = io.not_nil!.read_bytes(UInt32 ).as(UInt32 )
2844 end
45+
46+ def _write_ {{name.id}}(io : IO )
47+ io.not_nil!.write_bytes(@{{name.id}}.not_nil!)
48+ end
2949 end
3050
3151 macro uint16 (name )
@@ -34,6 +54,10 @@ class BinaryParser
3454 def _read_ {{name.id}}(io : IO )
3555 @{{name.id}} = io.not_nil!.read_bytes(UInt16 ).as(UInt16 )
3656 end
57+
58+ def _write_ {{name.id}}(io : IO )
59+ io.not_nil!.write_bytes(@{{name.id}}.not_nil!)
60+ end
3761 end
3862
3963 macro uint8 (name )
@@ -42,6 +66,10 @@ class BinaryParser
4266 def _read_ {{name.id}}(io : IO )
4367 @{{name.id}} = io.not_nil!.read_bytes(UInt8 ).as(UInt8 )
4468 end
69+
70+ def _write_ {{name.id}}(io : IO )
71+ io.not_nil!.write_bytes(@{{name.id}}.not_nil!)
72+ end
4573 end
4674
4775 macro int32 (name )
@@ -50,6 +78,10 @@ class BinaryParser
5078 def _read_ {{name.id}}(io : IO )
5179 @{{name.id}} = io.not_nil!.read_bytes(Int32 ).as(Int32 )
5280 end
81+
82+ def _write_ {{name.id}}(io : IO )
83+ io.not_nil!.write_bytes(@{{name.id}}.not_nil!)
84+ end
5385 end
5486
5587 macro int16 (name )
@@ -58,6 +90,10 @@ class BinaryParser
5890 def _read_ {{name.id}}(io : IO )
5991 @{{name.id}} = io.not_nil!.read_bytes(Int16 ).as(Int16 )
6092 end
93+
94+ def _write_ {{name.id}}(io : IO )
95+ io.not_nil!.write_bytes(@{{name.id}}.not_nil!)
96+ end
6197 end
6298
6399 macro int8 (name )
@@ -66,6 +102,10 @@ class BinaryParser
66102 def _read_ {{name.id}}(io : IO )
67103 @{{name.id}} = io.not_nil!.read_bytes(Int8 ).as(Int8 )
68104 end
105+
106+ def _write_ {{name.id}}(io : IO )
107+ io.not_nil!.write_bytes(@{{name.id}}.not_nil!)
108+ end
69109 end
70110
71111 macro char (name )
0 commit comments