Class: MemoryIO::IO
- Inherits:
-
Object
- Object
- MemoryIO::IO
- Defined in:
- lib/memory_io/io.rb
Overview
Main class to use MemoryIO.
Instance Attribute Summary collapse
-
#context ⇒ Object
readonly
Returns the value of attribute context.
-
#stream ⇒ #pos, ...
readonly
The stream given at instantiation.
Instance Method Summary collapse
-
#initialize(stream, endian: :native, pointer_size: MemoryIO::Context::DEFAULT_POINTER_SIZE) ⇒ IO
constructor
Instantiate an IO object.
-
#read(num_elements, from: nil, as: nil, force_array: false) ⇒ String, ...
Read and convert result into custom type/structure.
-
#rewind ⇒ 0
Set
streamto the beginning. -
#write(objects, from: nil, as: nil) ⇒ void
Write to stream.
Constructor Details
#initialize(stream, endian: :native, pointer_size: MemoryIO::Context::DEFAULT_POINTER_SIZE) ⇒ IO
Instantiate an MemoryIO::IO object.
34 35 36 37 38 |
# File 'lib/memory_io/io.rb', line 34 def initialize(stream, endian: :native, pointer_size: MemoryIO::Context::DEFAULT_POINTER_SIZE) @stream = stream @context = MemoryIO::Context.new(endian: endian, pointer_size: pointer_size) @tagged = MemoryIO::Stream.new(stream, @context) end |
Instance Attribute Details
#context ⇒ Object (readonly)
Returns the value of attribute context.
15 |
# File 'lib/memory_io/io.rb', line 15 attr_reader :stream, :context |
#stream ⇒ #pos, ... (readonly)
Returns The stream given at instantiation.
15 16 17 |
# File 'lib/memory_io/io.rb', line 15 def stream @stream end |
Instance Method Details
#read(num_elements, from: nil, as: nil, force_array: false) ⇒ String, ...
Note:
This method's arguments and return value are different with ::IO#read.
Check documents and examples.
Read and convert result into custom type/structure.
136 137 138 139 140 141 142 143 144 145 146 147 148 |
# File 'lib/memory_io/io.rb', line 136 def read(num_elements, from: nil, as: nil, force_array: false) unless num_elements.is_a?(Integer) && !num_elements.negative? raise ArgumentError, "num_elements must be a non-negative Integer, got #{num_elements.inspect}" end stream.pos = from if from return stream.read(num_elements) if as.nil? conv = to_proc(as, :read) ret = read_elements(num_elements, conv) ret = ret.first if num_elements == 1 && !force_array ret end |
#rewind ⇒ 0
Set stream to the beginning.
i.e. invoke stream.pos = 0.
213 214 215 |
# File 'lib/memory_io/io.rb', line 213 def rewind stream.pos = 0 end |
#write(objects, from: nil, as: nil) ⇒ void
This method returns an undefined value.
Write to stream.
200 201 202 203 204 205 206 207 |
# File 'lib/memory_io/io.rb', line 200 def write(objects, from: nil, as: nil) stream.pos = from if from as ||= objects.class if objects.class.ancestors.include?(MemoryIO::Types::Type) return stream.write(objects) if as.nil? conv = to_proc(as, :write) Array(objects).map { |o| conv.call(@tagged, o) } end |