Line | |
---|
1 | # TruncatedDataError is raised when IO#readbytes fails to read enough data.
|
---|
2 |
|
---|
3 | class TruncatedDataError<IOError
|
---|
4 | def initialize(mesg, data) # :nodoc:
|
---|
5 | @data = data
|
---|
6 | super(mesg)
|
---|
7 | end
|
---|
8 |
|
---|
9 | # The read portion of an IO#readbytes attempt.
|
---|
10 | attr_reader :data
|
---|
11 | end
|
---|
12 |
|
---|
13 | class IO
|
---|
14 | # Reads exactly +n+ bytes.
|
---|
15 | #
|
---|
16 | # If the data read is nil an EOFError is raised.
|
---|
17 | #
|
---|
18 | # If the data read is too short a TruncatedDataError is raised and the read
|
---|
19 | # data is obtainable via its #data method.
|
---|
20 | def readbytes(n)
|
---|
21 | str = read(n)
|
---|
22 | if str == nil
|
---|
23 | raise EOFError, "End of file reached"
|
---|
24 | end
|
---|
25 | if str.size < n
|
---|
26 | raise TruncatedDataError.new("data truncated", str)
|
---|
27 | end
|
---|
28 | str
|
---|
29 | end
|
---|
30 | end
|
---|
31 |
|
---|
32 | if __FILE__ == $0
|
---|
33 | begin
|
---|
34 | loop do
|
---|
35 | print STDIN.readbytes(6)
|
---|
36 | end
|
---|
37 | rescue TruncatedDataError
|
---|
38 | p $!.data
|
---|
39 | raise
|
---|
40 | end
|
---|
41 | end
|
---|
Note:
See
TracBrowser
for help on using the repository browser.