Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(octetcounting): re-use readers #18

Merged
merged 1 commit into from
Sep 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions octetcounting/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,14 @@ import (
"io"

syslog "github.com/leodido/go-syslog/v4"
"github.com/leodido/go-syslog/v4/rfc5424"
"github.com/leodido/go-syslog/v4/rfc3164"
"github.com/leodido/go-syslog/v4/rfc5424"
)

// parser is capable to parse the input stream containing syslog messages with octetcounting framing.
//
// Use NewParser function to instantiate one.
type parser struct {
msglen int64
maxMessageLength int
s Scanner
internal syslog.Machine
Expand Down Expand Up @@ -96,6 +95,7 @@ func (p *parser) Parse(r io.Reader) {
}

func (p *parser) run() {
defer p.s.Release()
for {
var tok Token

Expand Down
36 changes: 35 additions & 1 deletion octetcounting/scanner.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,38 @@ import (
"bytes"
"io"
"strconv"
"sync"
)

var readerPool sync.Pool

// getReader returns a *bufio.Reader that is guaranteed
// to have a buffer of at least `size`.
func getReader(r io.Reader, size int) *bufio.Reader {
if buf := readerPool.Get(); buf != nil {
buf := buf.(*bufio.Reader)

// If the buffer we get is smaller than the requested buffer, put it back
// and create a new one. stdlib has multiple buckets for various sizes to
// make this more efficient, but that's overkill here.
if buf.Size() < size {
readerPool.Put(buf)
buf = bufio.NewReaderSize(r, size)
} else {
buf.Reset(r)
}

return buf
}

return bufio.NewReaderSize(r, size)
}

// putReader returns the given bufio.Reader to the pool to be used again.
func putReader(r *bufio.Reader) {
readerPool.Put(r)
}

// eof represents a marker byte for the end of the reader
var eof = byte(0)

Expand Down Expand Up @@ -39,7 +69,7 @@ type Scanner struct {
// NewScanner returns a pointer to a new instance of Scanner.
func NewScanner(r io.Reader, maxLength int) *Scanner {
return &Scanner{
r: bufio.NewReaderSize(r, maxLength+20), // max uint64 is 19 characters + a space
r: getReader(r, maxLength+20), // max uint64 is 19 characters + a space
}
}

Expand Down Expand Up @@ -151,3 +181,7 @@ func (s *Scanner) scanSyslogMsg() Token {
lit: b,
}
}

func (s *Scanner) Release() {
putReader(s.r)
}