From 307a077b6071adc6947c52f227ac29b9668d9f13 Mon Sep 17 00:00:00 2001 From: Ayman Bagabas Date: Fri, 13 Sep 2024 10:12:29 -0400 Subject: [PATCH] feat(ansi): add parser pool to get/put parsers in a thread-safe manner --- ansi/parser_sync.go | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 ansi/parser_sync.go diff --git a/ansi/parser_sync.go b/ansi/parser_sync.go new file mode 100644 index 0000000..562e806 --- /dev/null +++ b/ansi/parser_sync.go @@ -0,0 +1,26 @@ +package ansi + +import ( + "sync" + + "github.com/charmbracelet/x/ansi/parser" +) + +var parserPool = sync.Pool{ + New: func() any { + return NewParser(parser.MaxParamsSize, 1024*4) // 4MB data buffer + }, +} + +// GetParser returns a parser from a sync pool. +func GetParser() *Parser { + return parserPool.Get().(*Parser) +} + +// PutParser returns a parser to a sync pool. The parser is reset +// automatically. +func PutParser(p *Parser) { + p.Reset() + p.DataLen = 0 + parserPool.Put(p) +}