github.com/searKing/golang/go@v1.2.117/io/watcher.go (about) 1 // Copyright 2020 The searKing Author. 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 5 package io 6 7 import "io" 8 9 type Watcher interface { 10 Watch(p []byte, n int, err error) (int, error) 11 } 12 type WatcherFunc func(p []byte, n int, err error) (int, error) 13 14 func (f WatcherFunc) Watch(p []byte, n int, err error) (int, error) { 15 return f(p, n, err) 16 } 17 18 type watchReader struct { 19 source io.Reader 20 watcher Watcher 21 } 22 23 func (r *watchReader) Read(p []byte) (int, error) { 24 var dummy io.Reader 25 if r == nil || r.source == nil { 26 dummy = EOFReader() 27 } else { 28 dummy = r.source 29 } 30 n, err := dummy.Read(p) 31 if r.watcher == nil { 32 return n, err 33 } 34 return r.watcher.Watch(p, n, err) 35 } 36 37 // WatchReader returns a Reader that's watch the Read state of 38 // the provided input reader. 39 func WatchReader(r io.Reader, watcher Watcher) io.Reader { 40 return &watchReader{source: r, watcher: watcher} 41 }