Class: StringIO

Inherits:
Object
  • Object
show all
Defined in:
lib/stringio_additions.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

.allocate(size) ⇒ StringIO

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



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

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

Instance Method Details

#byteFixnum

Reads a single byte from the current position of the byte stream



27
28
29
# File 'lib/stringio_additions.rb', line 27

def byte
  read(1)[0].ord
end

#cstringString

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

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



87
88
89
# File 'lib/stringio_additions.rb', line 87

def cstring
  gets("\0")[0..-2]
end

#floatFloat

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



35
36
37
# File 'lib/stringio_additions.rb', line 35

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



44
45
46
# File 'lib/stringio_additions.rb', line 44

def get
  read remaining
end

#longFixnum

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



52
53
54
# File 'lib/stringio_additions.rb', line 52

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



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

def remaining
  size - pos
end

#shortFixnum

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



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

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



76
77
78
# File 'lib/stringio_additions.rb', line 76

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