Class: Ips::BinaryReader

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

Overview

Binary data reader for parsing IPS patch files.

This class provides methods to read various data types from binary data, including strings, integers of different sizes, and raw bytes.

Examples:

Reading from binary data

data = File.binread("patch.ips")
reader = Ips::BinaryReader.new(data)
header = reader.read_string(5) # => "PATCH"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ BinaryReader

Creates a new BinaryReader instance.

Parameters:

  • data (String) —

    the binary data to read from



28
29
30
# File 'lib/ips/binary_reader.rb', line 28

def initialize(data)
  @data = StringIO.new(data)
end

Instance Attribute Details

#data ⇒ StringIO (readonly)

Returns the internal StringIO object containing the binary data.

Returns:

  • (StringIO) —

    the internal StringIO object containing the binary data



22
23
24
# File 'lib/ips/binary_reader.rb', line 22

def data
  @data
end

Instance Method Details

#go_back(n_bytes) ⇒ Integer

Moves the read position backwards by a specified number of bytes.

Parameters:

  • n_bytes (Integer) —

    the number of bytes to move back

Returns:

  • (Integer) —

    the new position in the stream



68
69
70
# File 'lib/ips/binary_reader.rb', line 68

def go_back(n_bytes)
  @data.seek(-n_bytes, IO::SEEK_CUR)
end

#read_bytes(n_bytes) ⇒ String

Reads a specified number of raw bytes from the current position.

Parameters:

  • n_bytes (Integer) —

    the number of bytes to read

Returns:

  • (String) —

    the raw bytes as a binary string



60
61
62
# File 'lib/ips/binary_reader.rb', line 60

def read_bytes(n_bytes)
  @data.read(n_bytes)
end

#read_int16 ⇒ Integer

Reads a 16-bit big-endian integer (2 bytes) from the current position.

Returns:

  • (Integer) —

    the 16-bit integer value



51
52
53
54
# File 'lib/ips/binary_reader.rb', line 51

def read_int16
  bytes = @data.read(2).bytes
  (bytes[0] << 8) | bytes[1]
end

#read_int24 ⇒ Integer

Reads a 24-bit big-endian integer (3 bytes) from the current position.

Returns:

  • (Integer) —

    the 24-bit integer value



43
44
45
46
# File 'lib/ips/binary_reader.rb', line 43

def read_int24
  bytes = @data.read(3).bytes
  (bytes[0] << 16) | (bytes[1] << 8) | bytes[2]
end

#read_string(size) ⇒ String

Reads a string of specified size from the current position.

Parameters:

  • size (Integer) —

    the number of bytes to read

Returns:

  • (String) —

    the string read from the data



36
37
38
# File 'lib/ips/binary_reader.rb', line 36

def read_string(size)
  @data.read(size)
end