Class: Mix1::Reader

Inherits:
Object
  • Object
show all
Defined in:
lib/mix1.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_path:, ignore_crc_mismatches: false, metadata_only: false, buffer_size: DEFAULT_BUFFER_SIZE) ⇒ Reader

Returns a new instance of Reader.



201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/mix1.rb', line 201

def initialize(file_path:, ignore_crc_mismatches: false, metadata_only: false, buffer_size: DEFAULT_BUFFER_SIZE)
  @package = Package.new

  @buffer = MemoryBuffer.new(file_path: file_path, mode: :read, buffer_size: buffer_size)

  @buffer.pos = 0

  # Valid header
  if read_i32 == 0x3158494D
    file_data_offset = read_i32
    file_names_offset = read_i32

    @buffer.pos = file_names_offset
    file_count = read_i32

    file_count.times do
      @package.files << Package::File.new(name: read_string)
    end

    @buffer.pos = file_data_offset
    @buffer.cache_file_data_chunk!

    _file_count = read_i32

    file_count.times do |i|
      file = @package.files[i]

      file.mix_crc = read_u32.to_s(16).rjust(8, "0")
      file.content_offset = read_u32
      file.content_length = read_u32

      if !ignore_crc_mismatches && file.mix_crc != file.file_crc
        raise MixParserException, "CRC mismatch for #{file.name}. #{file.mix_crc.inspect} != #{file.file_crc.inspect}"
      end

      pos = @buffer.pos
      @buffer.pos = file.content_offset
      file.data = @buffer.read(file.content_length) unless 
      @buffer.pos = pos
    end
  else
    raise MixParserException, "Invalid MIX file"
  end
ensure
  @buffer&.close
  @buffer = nil # let GC collect
end

Instance Attribute Details

#packageObject (readonly)

Returns the value of attribute package.



199
200
201
# File 'lib/mix1.rb', line 199

def package
  @package
end

Instance Method Details

#read_i32Object



249
250
251
# File 'lib/mix1.rb', line 249

def read_i32
  @buffer.read(4).unpack1("l")
end

#read_stringObject



257
258
259
260
261
262
263
264
265
266
267
# File 'lib/mix1.rb', line 257

def read_string
  buffer = ""

  length = @buffer.readbyte

  length.times do
    buffer << @buffer.readbyte
  end

  buffer.strip
end

#read_u32Object



253
254
255
# File 'lib/mix1.rb', line 253

def read_u32
  @buffer.read(4).unpack1("L")
end