writer.go 674 B

1234567891011121314151617181920212223242526272829303132333435
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package iotest
  5. import "io"
  6. // TruncateWriter returns a Writer that writes to w
  7. // but stops silently after n bytes.
  8. func TruncateWriter(w io.Writer, n int64) io.Writer {
  9. return &truncateWriter{w, n}
  10. }
  11. type truncateWriter struct {
  12. w io.Writer
  13. n int64
  14. }
  15. func (t *truncateWriter) Write(p []byte) (n int, err error) {
  16. if t.n <= 0 {
  17. return len(p), nil
  18. }
  19. // real write
  20. n = len(p)
  21. if int64(n) > t.n {
  22. n = int(t.n)
  23. }
  24. n, err = t.w.Write(p[0:n])
  25. t.n -= int64(n)
  26. if err == nil {
  27. n = len(p)
  28. }
  29. return
  30. }