Skip to content

Commit

Permalink
color: expose SetWriter and UnsetWriter
Browse files Browse the repository at this point in the history
For some users performance is very important and hence having access to
the underlying writer functions allow them to use bytes buffer and avoid
string allocations.

closes #124
  • Loading branch information
fatih committed Jan 22, 2023
1 parent 6378f62 commit 7310c74
Showing 1 changed file with 13 additions and 8 deletions.
21 changes: 13 additions & 8 deletions color.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,10 @@ func (c *Color) unset() {
Unset()
}

func (c *Color) setWriter(w io.Writer) *Color {
// SetWriter is used to set the SGR sequence with the given io.Writer. This is
// a low-level function, and users should use the higher-level functions, such
// as color.Fprint, color.Print, etc.
func (c *Color) SetWriter(w io.Writer) *Color {
if c.isNoColorSet() {
return c
}
Expand All @@ -172,7 +175,9 @@ func (c *Color) setWriter(w io.Writer) *Color {
return c
}

func (c *Color) unsetWriter(w io.Writer) {
// UnsetWriter resets all escape attributes and clears the output with the give
// io.Writer. Usually should be called after SetWriter().
func (c *Color) UnsetWriter(w io.Writer) {
if c.isNoColorSet() {
return
}
Expand All @@ -197,8 +202,8 @@ func (c *Color) Add(value ...Attribute) *Color {
// On Windows, users should wrap w with colorable.NewColorable() if w is of
// type *os.File.
func (c *Color) Fprint(w io.Writer, a ...interface{}) (n int, err error) {
c.setWriter(w)
defer c.unsetWriter(w)
c.SetWriter(w)
defer c.UnsetWriter(w)

return fmt.Fprint(w, a...)
}
Expand All @@ -220,8 +225,8 @@ func (c *Color) Print(a ...interface{}) (n int, err error) {
// On Windows, users should wrap w with colorable.NewColorable() if w is of
// type *os.File.
func (c *Color) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
c.setWriter(w)
defer c.unsetWriter(w)
c.SetWriter(w)
defer c.UnsetWriter(w)

return fmt.Fprintf(w, format, a...)
}
Expand All @@ -241,8 +246,8 @@ func (c *Color) Printf(format string, a ...interface{}) (n int, err error) {
// On Windows, users should wrap w with colorable.NewColorable() if w is of
// type *os.File.
func (c *Color) Fprintln(w io.Writer, a ...interface{}) (n int, err error) {
c.setWriter(w)
defer c.unsetWriter(w)
c.SetWriter(w)
defer c.UnsetWriter(w)

return fmt.Fprintln(w, a...)
}
Expand Down

0 comments on commit 7310c74

Please sign in to comment.