Class: StringIO

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

Overview

This extends the StringIO class from Ruby's standard library. It adds some methods to handle byte-wise input from a StringIO object.

Author:

  • Sebastian Staudt

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.alloc(size) ⇒ StringIO

Creates a new instance of StringIO with the given size and fills it with zero-bytes.

Parameters:

  • size (Fixnum)

    The size the new instance should have

Returns:

  • (StringIO)

    A new StringIO instance with the given size, filled with zero-bytes


20
21
22
# File 'lib/core_ext/stringio.rb', line 20

def self.alloc(size)
  new "\0" * size
end

Instance Method Details

#cstringString

Reads a zero-byte terminated string from the current position of the byte stream

This reads the stream up until the first occurrence of a zero-byte or the end of the stream. The zero-byte is not included in the returned string.

Returns:

  • (String)

    The zero-byte terminated string read from the byte stream


80
81
82
83
84
# File 'lib/core_ext/stringio.rb', line 80

def cstring
  string = gets("\0")[0..-2]
  string.force_encoding 'UTF-8' if string.respond_to? :force_encoding
  string
end

#floatFloat

Reads a floating-point integer (32 bit) from the current position of the byte stream

Returns:

  • (Float)

    The floating-point integer read from the byte stream


28
29
30
# File 'lib/core_ext/stringio.rb', line 28

def float
  read(4).unpack('e')[0]
end

#getString

Reads the whole remaining content of the byte stream from the current position to the end

Returns:

  • (String)

    The remainder of the byte stream starting from the current position of the byte stream


37
38
39
# File 'lib/core_ext/stringio.rb', line 37

def get
  read remaining
end

#longFixnum

Reads an unsigned long integer (32 bit) from the current position of the byte stream

Returns:

  • (Fixnum)

    The unsigned long integer read from the byte stream


45
46
47
# File 'lib/core_ext/stringio.rb', line 45

def long
  read(4).unpack('V')[0]
end

#remainingFixnum

Returns the remaining number of bytes from the current position to the end of the byte stream

Returns:

  • (Fixnum)

    The number of bytes until the end of the stream


53
54
55
# File 'lib/core_ext/stringio.rb', line 53

def remaining
  size - pos
end

#shortFixnum

Reads an unsigned short integer (16 bit) from the current position of the byte stream

Returns:

  • (Fixnum)

    The unsigned short integer read from the byte stream


61
62
63
# File 'lib/core_ext/stringio.rb', line 61

def short
  read(2).unpack('v')[0]
end

#signed_longFixnum

Reads a signed long integer (32 bit) from the current position of the byte stream

Returns:

  • (Fixnum)

    The signed long integer read from the byte stream


69
70
71
# File 'lib/core_ext/stringio.rb', line 69

def signed_long
  read(4).unpack('l')[0]
end