Class: Feh::Bin::ArrayIStream

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/feh/bin/array_istream.rb

Overview

Single-pass input array stream that reads little-endian integers.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(buffer) ⇒ ArrayIStream

Initializes the stream.

Parameters:

  • buffer (Array<Integer>)

    an array of byte values between 0 and 255

Raises:

  • (ArgumentError)

    if arr is not a byte array


20
21
22
23
24
25
26
# File 'lib/feh/bin/array_istream.rb', line 20

def initialize(buffer)
  raise ArgumentError, 'Input is not a byte array' unless
    buffer.is_a?(Array) &&
    buffer.all? {|x| x.is_a?(Integer) && x.between?(0, 255)}
  @buf = buffer
  @bytes_read = 0
end

Instance Attribute Details

#bytes_readInteger (readonly)

Returns the number of bytes read so far.

Returns:

  • (Integer)

    the number of bytes read so far


15
16
17
# File 'lib/feh/bin/array_istream.rb', line 15

def bytes_read
  @bytes_read
end

#sizeInteger (readonly)

Returns the size of the underlying array stream.

Returns:

  • (Integer)

    the size of the underlying array stream


12
# File 'lib/feh/bin/array_istream.rb', line 12

def_delegators :@buf, :[], :size

Instance Method Details

#remainingArray<Integer>

Returns the unread bytes of the stream.

Returns:

  • (Array<Integer>)

    An array of unread bytes.


64
65
66
# File 'lib/feh/bin/array_istream.rb', line 64

def remaining
  @buf[@bytes_read..-1]
end

#u16Integer?

Attempts to read an unsigned 16-bit integer.

Returns:

  • (Integer)

    the integer read

  • (nil)

    if not enough bytes remaining are present to form an integer


41
42
43
44
45
46
47
# File 'lib/feh/bin/array_istream.rb', line 41

def u16
  return nil if @bytes_read > @buf.size - 2
  x = @buf[@bytes_read]
  x |= @buf[@bytes_read + 1] << 8
  @bytes_read += 2
  x
end

#u32Integer?

Attempts to read an unsigned 32-bit integer.

Returns:

  • (Integer)

    the integer read

  • (nil)

    if not enough bytes remaining are present to form an integer


52
53
54
55
56
57
58
59
60
# File 'lib/feh/bin/array_istream.rb', line 52

def u32
  return nil if @bytes_read > @buf.size - 4
  x = @buf[@bytes_read]
  x |= @buf[@bytes_read + 1] << 8
  x |= @buf[@bytes_read + 2] << 16
  x |= @buf[@bytes_read + 3] << 24
  @bytes_read += 4
  x
end

#u8Integer?

Attempts to read an unsigned 8-bit integer.

Returns:

  • (Integer)

    the integer read

  • (nil)

    if not enough bytes remaining are present to form an integer


31
32
33
34
35
36
# File 'lib/feh/bin/array_istream.rb', line 31

def u8
  return nil if @bytes_read > @buf.size - 1
  x = @buf[@bytes_read]
  @bytes_read += 1
  x
end