/tools/Ruby/lib/ruby/1.8/readbytes.rb

http://github.com/agross/netopenspace · Ruby · 41 lines · 29 code · 4 blank · 8 comment · 5 complexity · fb5aac253fd8332686741879c4070338 MD5 · raw file

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