6

I'm writing some code that needs functionality that is almost satisfied by the ReadBytes method in the bufio package. Specifically, that method reads from a Reader until it encounters a particular byte. I need something that reads till it encounters one out of couple of bytes (space, newline and tab mainly).

I looked at the source for the library and I know what to do if I have access to the internal buffer used by bufio structs. Is there any way I could "monkey patch" the package and add another method or two to it? Or another way to get the functionality I need?

2
  • 1
    A major reason there are private hidden fields is to make it possible for the implementation to evolve in the future without impacting users. Allowing you to access byte would break this guarantee. So I don't see other proper way than to make your own (limited) Reader struct and method. May 30, 2012 at 11:45
  • 2
    Your question is about one solution (enhancing bufio) you have in mind for your real problem (reading a certain data format.) As the answers and comments indicate, the package features of Go were actually engineered to obstruct you from doing that. It might be better to consider other solutions, or even post another question on SO with details of your data format and ask, "what's a good way of reading this multiple-delimiter format?"
    – Sonia
    May 30, 2012 at 23:05

2 Answers 2

5

Something along this approach (caution: untested code):

type reader struct{
        *bufio.Reader // 'reader' inherits all bufio.Reader methods
}

func newReader(rd io.Reader) reader {
        return reader{bufio.NewReader(rd)}
}

// Override bufio.Reader.ReadBytes
func (r reader) ReadBytes(delim byte) (line []byte, err error) {
        // here goes the monkey patch
}

// Or

// Add a new method to bufio.Reader
func (r reader) ReadBytesEx(delims []byte) (line []byte, err error) {
        // here goes the new code
}

EDIT: I should have noted that this doesn't help to access the original package internals (non exported entities). Thanks Abhay for pointing that out in your comment.

2
  • Can you access the unexported fields of bufio.Reader this way ? May 30, 2012 at 11:48
  • 1
    Unfortunately no, this seems to result in the calls being delegated to the inner struct. The whole struct is still embedded in the new one and is still treated like a separate entity. You don't actually have access to it's package local variables. Thanks for the attempt though!
    – Abhay Buch
    May 30, 2012 at 11:54
1

It's usually best to solve problems using the package API. If you have a compelling reason to access unexported features though, copy the package source and hack it up. The BSD-style license as about as liberal as they come.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.