scanner.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package bencode
  2. import (
  3. "errors"
  4. "io"
  5. )
  6. // Implements io.ByteScanner over io.Reader, for use in Decoder, to ensure
  7. // that as little as the undecoded input Reader is consumed as possible.
  8. type scanner struct {
  9. r io.Reader
  10. b [1]byte // Buffer for ReadByte
  11. unread bool // True if b has been unread, and so should be returned next
  12. }
  13. func (me *scanner) Read(b []byte) (int, error) {
  14. return me.r.Read(b)
  15. }
  16. func (me *scanner) ReadByte() (byte, error) {
  17. if me.unread {
  18. me.unread = false
  19. return me.b[0], nil
  20. }
  21. for {
  22. n, err := me.r.Read(me.b[:])
  23. switch n {
  24. case 0:
  25. // io.Reader.Read says to try again if there's no error and no bytes returned. We can't
  26. // signal that the caller should do this method's interface.
  27. if err != nil {
  28. return 0, err
  29. }
  30. panic(err)
  31. case 1:
  32. // There's no way to signal that the byte is valid unless error is nil.
  33. return me.b[0], nil
  34. default:
  35. if err != nil {
  36. // I can't see why Read would return more bytes than expected, but the error should
  37. // tell us why.
  38. panic(err)
  39. }
  40. panic(n)
  41. }
  42. }
  43. }
  44. func (me *scanner) UnreadByte() error {
  45. if me.unread {
  46. return errors.New("byte already unread")
  47. }
  48. me.unread = true
  49. return nil
  50. }