11require " ./binary_parser/macros/*"
22
3+ # BinaryParser for Crystal
4+ #
5+ # ```crystal
6+ # class Parser < BinaryParser
7+ # uint8 :value
8+ # end
9+ #
10+ # io = IO::Memory.new(sizeof(UInt8))
11+ # io.write_bytes(42)
12+ # io.rewind
13+ # parser = Parser.new.load(io)
14+ #
15+ # parser.value # 42
16+ # ```
17+ #
318class BinaryParser
19+
20+ # Load from file with `filename`
21+ #
422 def load (filename : String )
523 io = File .open(filename)
624 load(io)
725 end
826
27+ # Load from an IO object
28+ #
929 def load (io : IO )
1030 {% for method in @type .methods % }
1131 {% if method.name.starts_with?(" _read_" ) % }
@@ -15,15 +35,25 @@ class BinaryParser
1535 self
1636 end
1737
38+ # Save to file with `filename`
39+ #
1840 def save (filename : String )
1941 io = File .open(filename, " w" )
2042 write(io)
2143 end
2244
45+ # Convert to string
46+ #
47+ # ```crystal
48+ # File.write("filename", parser)
49+ # ```
50+ #
2351 def to_s (io : IO )
2452 write(io)
2553 end
2654
55+ # Write to an IO object
56+ #
2757 def write (io : IO )
2858 {% for method in @type .methods % }
2959 {% if method.name.starts_with?(" _write_" ) % }
@@ -33,11 +63,17 @@ class BinaryParser
3363 self
3464 end
3565
66+ # Support for `IO#read_bytes`
67+ #
68+ # **NOTICE**: Current not respect to `IO::ByteFormat`
3669 def self.from_io (io : IO , format : IO ::ByteFormat )
3770 ins = self .new
3871 ins.load(io)
3972 end
4073
74+ # Support for `IO#write_bytes`
75+ #
76+ # **NOTICE**: Current not respect to `IO::ByteFormat`
4177 def to_io (io : IO , format : IO ::ByteFormat )
4278 write(io)
4379 end
0 commit comments