github.com/Bytom/bytom@v1.1.2-0.20210127130405-ae40204c0b09/errors/writer.go (about) 1 package errors 2 3 import "io" 4 5 // NewWriter returns a new Writer that writes to w 6 // until an error is returned. 7 func NewWriter(w io.Writer) *Writer { 8 return &Writer{w: w} 9 } 10 11 // Writer is in an implementation of the 12 // "sticky error writer" pattern as described 13 // in https://blog.golang.org/errors-are-values. 14 // 15 // A Writer makes one call 16 // on the underlying writer for each call to Write, 17 // until an error is returned. From that point on, 18 // it makes no calls on the underlying writer, 19 // and returns the same error value every time. 20 type Writer struct { 21 w io.Writer 22 n int64 23 err error 24 } 25 26 // Write makes one call on the underlying writer 27 // if no error has previously occurred. 28 func (w *Writer) Write(buf []byte) (n int, err error) { 29 if w.err != nil { 30 return 0, w.err 31 } 32 n, w.err = w.w.Write(buf) 33 w.n += int64(n) 34 return n, w.err 35 } 36 37 // Err returns the first error encountered by Write, if any. 38 func (w *Writer) Err() error { 39 return w.err 40 } 41 42 // Written returns the number of bytes written 43 // to the underlying writer. 44 func (w *Writer) Written() int64 { 45 return w.n 46 }