-
Notifications
You must be signed in to change notification settings - Fork 0
/
teeread.go
59 lines (46 loc) · 1.81 KB
/
teeread.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package ioop
import (
"io"
"strings"
"github.com/devlights/gomy/output"
)
// byteCounter は、書き込まれたバイト数を数える特殊 io.Writer です。
type byteCounter int
func (me *byteCounter) Write(p []byte) (n int, err error) {
*me = byteCounter(int(*me) + len(p))
return len(p), nil
}
// TeeRead は、io.TeeReader を利用したサンプルです。
//
// io.TeeReader は、teeコマンドと同じような動きをする。読み取ったデータは戻り値のReaderを経由して取得し、さらに引数で指定したio.Writerにも書き込まれる。
//
// > TeeReader returns a Reader that writes to w what it reads from r. All reads from r performed through it are matched with corresponding writes to w.
//
// > TeeReaderは、rから読み取ったものをwに書き込むReaderを返します。TeeReaderを介して実行されるrからのすべての読み取りは、対応するwへの書き込みと一致します。
//
// io.TeeReaderには、内部バッファを持っていない。
// なので、rから読み取ったデータは即時wに書き込まないとブロックされてしまう。
//
// # REFERENCES
// - https://pkg.go.dev/io@go1.22.2#TeeReader
// - https://cs.opensource.google/go/go/+/refs/tags/go1.22.2:src/io/io.go;l=618
func TeeRead() error {
r := strings.NewReader("helloworld こんにちは世界")
w := byteCounter(0)
b, _ := io.ReadAll(io.TeeReader(r, &w))
output.Stdoutl("[r]", string(b))
output.StdoutHr()
output.Stdoutl("[w]", int(w))
return nil
/*
$ task
task: [build] go build .
task: [run] ./try-golang -onetime
ENTER EXAMPLE NAME: ioop_tee_read
[Name] "ioop_tee_read"
[r] helloworld こんにちは世界
--------------------------------------------------
[w] 32
[Elapsed] 34.05µs
*/
}