| 1 | package limio |
| 2 | |
| 3 | import "io" |
| 4 | |
| 5 | type limitedWriter struct { |
| 6 | W io.Writer |
| 7 | N int64 |
| 8 | } |
| 9 | |
| 10 | func (l *limitedWriter) Write(p []byte) (n int, err error) { |
| 11 | if l.N <= 0 { |
| 12 | return 0, io.ErrShortWrite |
| 13 | } |
| 14 | if int64(len(p)) > l.N { |
| 15 | p = p[0:l.N] |
| 16 | err = io.ErrShortWrite |
| 17 | } |
| 18 | n, er := l.W.Write(p) |
| 19 | if er != nil { |
| 20 | err = er |
| 21 | } |
| 22 | l.N -= int64(n) |
| 23 | return n, err |
| 24 | } |
| 25 | |
| 26 | // LimitWriter works like io.LimitReader. It writes at most n bytes |
| 27 | // to the underlying Writer. It returns io.ErrShortWrite if more than n |
| 28 | // bytes are attempted to be written. |
| 29 | func LimitWriter(w io.Writer, n int64) io.Writer { |
| 30 | return &limitedWriter{W: w, N: n} |
| 31 | } |