Skip to content

Commit

Permalink
Re-use Syslog Readers
Browse files Browse the repository at this point in the history
Signed-off-by: sinkingpoint <[email protected]>
  • Loading branch information
sinkingpoint authored and leodido committed Sep 18, 2024
1 parent f4af6ad commit 42a2959
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
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)
}

0 comments on commit 42a2959

Please sign in to comment.