Class: IO

Inherits:
Object show all
Includes:
CosmosIO
Defined in:
lib/cosmos/core_ext/io.rb

Constant Summary collapse

SELECT_BASE_TIMEOUT =
0.0004
SELECT_MAX_TIMEOUT =
0.016

Class Method Summary collapse

Methods included from CosmosIO

#read_length_bytes

Class Method Details

.fast_read_select(read_sockets, timeout) ⇒ Object

fast_select



68
69
70
# File 'lib/cosmos/core_ext/io.rb', line 68

def self.fast_read_select(read_sockets, timeout)
  return fast_select(read_sockets, nil, nil, timeout)
end

.fast_select(read_sockets = nil, write_sockets = nil, error_array = nil, timeout = nil) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/cosmos/core_ext/io.rb', line 19

def self.fast_select(read_sockets = nil, write_sockets = nil, error_array = nil, timeout = nil)
  # Always try a zero timeout first
  current_timeout = SELECT_BASE_TIMEOUT
  total_timeout = 0.0

  while true
    result = IO.select(read_sockets, write_sockets, error_array, current_timeout)
    return result if result or current_timeout.nil?
    return nil if timeout and total_timeout >= timeout

    if current_timeout <= 0.0001
      # Always try the base timeout next
      current_timeout = SELECT_BASE_TIMEOUT
      total_timeout = SELECT_BASE_TIMEOUT
    else
      # Then start doubling the timeout
      current_timeout = current_timeout * 2

      # Until it is bigger than our max timeout
      if current_timeout >= SELECT_MAX_TIMEOUT
        if timeout
          # Block for the remaining requested timeout
          current_timeout = timeout - total_timeout
          total_timeout = timeout
        else
          # Or block forever
          current_timeout = nil
        end
      else
        # Or it is bigger than the given timeout
        if timeout and current_timeout >= timeout
          # Block for the remaining requested timeout
          current_timeout = timeout - total_timeout
          total_timeout = timeout
        else
          # Up our total time in select
          total_timeout += current_timeout
        end
        if timeout and total_timeout > timeout
          # Block for the remaining requested timeout
          current_timeout = timeout - total_timeout
          total_timeout = timeout
        end
      end
      return nil if current_timeout and current_timeout < 0
    end
  end # while true
end

.fast_write_select(write_sockets, timeout) ⇒ Object



72
73
74
# File 'lib/cosmos/core_ext/io.rb', line 72

def self.fast_write_select(write_sockets, timeout)
  return fast_select(nil, write_sockets, nil, timeout)
end