Module: YABFI::Parser

Defined in:
lib/yabfi/parser.rb

Overview

This module contains a set of functions that lazily parse an IO object and yield a symbol for each non-comment character that is read in.

Constant Summary collapse

DEFAULT_BUFFER_SIZE =

Maximum number of bytes to read in from the IO object at a time.

1_024
COMMAND_MAPPINGS =

Maps characters to human-readable Symbol command names.

{
  '+' => :succ,
  '-' => :pred,
  '>' => :next,
  '<' => :prev,
  ',' => :get,
  '.' => :put,
  '[' => :loop,
  ']' => :end
}

Class Method Summary collapse

Class Method Details

.parse(io, buffer_size = DEFAULT_BUFFER_SIZE) {|command| ... } ⇒ Enumator<Symbol>

Lazily parse an IO object while it still has input.

Parameters:

  • io (IO)

    the object from which the parser lazily reads.

  • buffer_size (Integer) (defaults to: DEFAULT_BUFFER_SIZE)

    maximum size to request from the IO at once.

Yields:

  • (command)

    Symbol that represents the parsed command.

Returns:

  • (Enumator<Symbol>)

    of commands when no block is given.



28
29
30
31
32
33
34
35
36
37
38
# File 'lib/yabfi/parser.rb', line 28

def parse(io, buffer_size = DEFAULT_BUFFER_SIZE)
  return enum_for(:parse, io, buffer_size) unless block_given?
  loop do
    buffer = read(io, buffer_size)
    break unless buffer
    buffer.each_char do |char|
      command = COMMAND_MAPPINGS[char]
      yield command if command
    end
  end
end

.read(io, size) ⇒ String?

Block waiting for the next set of commands.

Parameters:

  • io (IO)

    the object from which the parser lazily reads.

  • size (Integer)

    the maximum number of bytes to read in.

Returns:

  • (String, nil)

    the buffer of bytes read in, or nil on EOF.



45
46
47
48
49
50
51
52
# File 'lib/yabfi/parser.rb', line 45

def read(io, size)
  io.read_nonblock(size)
rescue IO::WaitReadable
  IO.select([io])
  retry
rescue EOFError
  nil
end