wrap escBuf with sync.Pool
Vladimir Bauer
3 years ago
| 5 | 5 | "io" |
| 6 | 6 | "os" |
| 7 | 7 | "strconv" |
| 8 | "sync" | |
| 8 | 9 | ) |
| 9 | 10 | |
| 10 | 11 | // https://github.com/dylanaraps/pure-sh-bible#cursor-movement |
| 14 | 15 | ) |
| 15 | 16 | |
| 16 | 17 | // used by ansiCuuAndEd func |
| 17 | var escBuf = make([]byte, 8) | |
| 18 | var escBuf = sync.Pool{ | |
| 19 | New: func() interface{} { | |
| 20 | b := make([]byte, 8) | |
| 21 | return &b | |
| 22 | }, | |
| 23 | } | |
| 18 | 24 | |
| 19 | 25 | // ErrNotTTY not a TeleTYpewriter error. |
| 20 | 26 | var ErrNotTTY = errors.New("not a terminal") |
| 55 | 61 | return w.termSize(w.fd) |
| 56 | 62 | } |
| 57 | 63 | |
| 58 | // if n > 99 it will allocate because of len(escBuf) = 8 | |
| 64 | // if n > 99 it will allocate because escBuf.Get returns slice of length 8 | |
| 59 | 65 | func ansiCuuAndEd(out io.Writer, n int) error { |
| 60 | escBuf = strconv.AppendInt(escBuf[:copy(escBuf, escOpen)], int64(n), 10) | |
| 61 | _, err := out.Write(append(escBuf, cuuAndEd...)) | |
| 66 | bufp := escBuf.Get() | |
| 67 | buf := *bufp.(*[]byte) | |
| 68 | buf = strconv.AppendInt(buf[:copy(buf, escOpen)], int64(n), 10) | |
| 69 | _, err := out.Write(append(buf, cuuAndEd...)) | |
| 70 | escBuf.Put(bufp) | |
| 62 | 71 | return err |
| 63 | 72 | } |