forked from phlipper/ichannel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ichannel.rb
71 lines (67 loc) · 1.48 KB
/
ichannel.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
67
68
69
70
71
require 'socket'
class IChannel
#
# @param [#dump,#load}] serializer
# Any object that implements dump, & load.
#
def initialize(serializer)
@reader, @writer = UNIXSocket.pair Socket::SOCK_DGRAM
@serializer = serializer
end
#
# @return [Boolean]
# Returns true when the channel is closed.
#
def closed?
@reader.closed? && @writer.closed?
end
#
# Close the channel.
#
# @return [Boolean]
# Returns true when the channel has been closed.
# Returns nil when the channel is already closed.
#
def close
if !@reader.closed? && !@writer.closed?
!! [@reader.close, @writer.close]
end
end
#
# Add an object to the channel.
#
# @raise [IOError]
# When the channel cannot be written to.
#
# @param [Object] object
# An object to add to the channel.
#
def write(object)
_, writable, _ = IO.select [], [@writer], [], 0.1
if writable
@writer.send @serializer.dump(object), 0
else
raise IOError, 'The channel cannot be written to.'
end
end
alias_method :put, :write
#
# Receive a object from the channel.
#
# @raise [IOError]
# When the channel cannot be read from.
#
# @return [Object]
# The object added to the channel.
#
def recv
readable, _ = IO.select [@reader], [], [], 0.1
if readable
msg, _ = @reader.recvmsg
@serializer.load msg
else
raise IOError, 'The channel cannot be read from.'
end
end
alias_method :get, :recv
end