Chunk.deserialize fails if the given buffer is empty.
[ruby-eet.git] / lib / eet.rb
1 #--
2 # $Id: eet.rb 46 2005-05-25 20:10:37Z tilman $
3 #
4 # Copyright (c) 2005 Tilman Sauerbeck (tilman at code-monkey de)
5 #
6 # Permission is hereby granted, free of charge, to any person obtaining
7 # a copy of this software and associated documentation files (the
8 # "Software"), to deal in the Software without restriction, including
9 # without limitation the rights to use, copy, modify, merge, publish,
10 # distribute, sublicense, and/or sell copies of the Software, and to
11 # permit persons to whom the Software is furnished to do so, subject to
12 # the following conditions:
13 #
14 # The above copyright notice and this permission notice shall be
15 # included in all copies or substantial portions of the Software.
16 #
17 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21 # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22 # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23 # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24
25 require "eet_ext"
26
27 class Object
28         # :call-seq:
29         #  object.to_eet -> string
30         #
31         # Serializes the receiver to EET format.
32         def to_eet
33                 props = to_eet_properties
34
35                 unless props.is_a?(Hash) && !props.empty?
36                         raise(Eet::PropertyError, "invalid EET properties")
37                 end
38
39                 eet_name = to_eet_name
40
41                 if eet_name.to_str.length < 1 || eet_name.to_str.include?(0)
42                         raise(Eet::NameError, "invalid EET name")
43                 end
44
45                 stream = Eet::Stream.new
46
47                 props.each_pair do |tag, arg|
48                         unless arg.is_a?(Array)
49                                 raise(Eet::PropertyError, "hash value is not an array")
50                         end
51
52                         value, type = arg
53                         next if value.nil?
54
55                         stream.push(*value.to_eet_chunks(tag, type))
56                 end
57
58                 chunk = Eet::Chunk.new(eet_name, stream.serialize)
59                 Eet::Stream.new(chunk).serialize
60         end
61
62         def to_eet_chunks(tag, type = nil) # :nodoc:
63                 [Eet::Chunk.new(tag, to_eet)]
64         end
65
66         protected
67
68         # :call-seq:
69         #  object.to_eet_name -> string
70         #
71         # Returns the tag that's stored with the data for _object_.
72         # If your class doesn't override this method, the class name will be
73         # used.
74         def to_eet_name
75                 self.class.name
76         end
77
78         # :call-seq:
79         #  object.to_eet_properties -> hash
80         #
81         # Returns a hash that contains the properties that are stored for
82         # _object_.
83         # If your class doesn't override this method, all instance variables
84         # of _object_ will be stored.
85         def to_eet_properties
86                 instance_variables.inject({}) do |h, var|
87                         h[var[1..-1]] = [instance_variable_get(var)]
88                         h
89                 end
90         end
91 end
92
93 class Integer # :nodoc:
94         def to_eet_chunks(tag, type = nil)
95                 fmt = case type
96                 when :char: "c"
97                 when :short: "v"
98                 when :long_long: "q"
99                 else "V"
100                 end
101
102                 data = [self].pack(fmt)
103                 [Eet::Chunk.new(tag, data)]
104         end
105 end
106
107 class Float # :nodoc:
108         def to_eet_chunks(tag, type = nil)
109                 fmt = case type
110                 when :double: "%32.32f"
111                 else "%16.16f"
112                 end
113
114                 data = fmt % self
115                 [Eet::Chunk.new(tag, data + "\0")]
116         end
117 end
118
119 class String # :nodoc:
120         def to_eet_chunks(tag, type = nil)
121                 [Eet::Chunk.new(tag, self + "\0")]
122         end
123 end
124
125 class TrueClass # :nodoc:
126         def to_eet_chunks(tag, type = nil)
127                 [Eet::Chunk.new(tag, "\1")]
128         end
129 end
130
131 class FalseClass # :nodoc:
132         def to_eet_chunks(tag, type = nil)
133                 [Eet::Chunk.new(tag, "\0")]
134         end
135 end
136
137 class Array # :nodoc:
138         def to_eet_chunks(tag, type = nil)
139                 case type
140                 when :sub
141                         [Eet::Chunk.new(tag, self.to_eet)]
142                 else
143                         # lists always hold subtypes
144                         map { |item| Eet::Chunk.new(tag, item.to_eet) }
145                 end
146         end
147 end
148
149 class Hash # :nodoc:
150         def to_eet_chunks(tag, type = nil)
151                 # lists always hold subtypes
152                 map { |(key, value)| Eet::Chunk.new(tag, value.to_eet) }
153         end
154 end
155
156 module Eet
157         VERSION = "0.1.2"
158
159         class EetError < StandardError; end
160         class NameError < EetError; end
161         class PropertyError < EetError; end
162         class ChunkError < EetError; end
163
164         class Stream # :nodoc:
165                 def initialize(chunk = nil)
166                         super(chunk.nil? ? 0 : 1, chunk)
167                 end
168
169                 def Stream.deserialize(data)
170                         if data.to_str.empty?
171                                 raise(ArgumentError, "buffer is empty")
172                         end
173
174                         s = Stream.new
175                         offset = 0
176
177                         while offset < data.length
178                                 c, bytes = Chunk.deserialize(data[offset..-1])
179
180                                 s << c
181                                 offset += bytes
182                         end
183
184                         s
185                 end
186         end
187
188         class Chunk # :nodoc:
189                 attr_reader :tag, :data
190
191                 def initialize(tag, data)
192                         if tag.to_str.include?(0)
193                                 raise(ArgumentError,
194                                       "tag must not contain binary zeroes")
195                         end
196
197                         @tag = tag.to_str.dup.freeze
198                         @data = data.to_str.dup.freeze
199
200                         # libeet uses a signed 32bit integer to store the
201                         # chunk size, so make sure we don't overflow it
202                         if (@tag.length + 1 + @data.length) >= (1 << 31)
203                                 raise(ArgumentError, "tag or data too long")
204                         end
205                 end
206
207                 def Chunk.deserialize(data)
208                         if data.to_str.empty?
209                                 raise(ArgumentError, "buffer is empty")
210                         end
211
212                         if data.length < 8 || data[0, 4] != "CHnK"
213                                 raise(ChunkError, "invalid data")
214                         end
215
216                         size = data[4, 4].unpack("V").first
217                         if size >= (1 << 31) || size > data.length - 8
218                                 raise(ChunkError, "invalid chunk size")
219                         end
220
221                         unless data[8, size].include?(0)
222                                 raise(ChunkError, "invalid chunk data")
223                         end
224
225                         c = Chunk.new(*data[8, size].split("\0", 2))
226
227                         [c, 8 + size]
228                 end
229         end
230 end