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