github.com/jbendotnet/noms@v0.0.0-20190904222105-c43e4293ea92/go/util/progressreader/reader.go (about) 1 // Copyright 2016 Attic Labs, Inc. All rights reserved. 2 // Licensed under the Apache License, version 2.0: 3 // http://www.apache.org/licenses/LICENSE-2.0 4 5 // Package progressreader provides an io.Reader that reports progress to a callback 6 package progressreader 7 8 import ( 9 "io" 10 "time" 11 12 "github.com/attic-labs/noms/go/util/status" 13 ) 14 15 type Callback func(seen uint64) 16 17 func New(inner io.Reader, cb Callback) io.Reader { 18 return &reader{inner, uint64(0), time.Time{}, cb} 19 } 20 21 type reader struct { 22 inner io.Reader 23 seen uint64 24 lastTime time.Time 25 cb Callback 26 } 27 28 func (r *reader) Read(p []byte) (n int, err error) { 29 n, err = r.inner.Read(p) 30 r.seen += uint64(n) 31 32 if now := time.Now(); now.Sub(r.lastTime) >= status.Rate || err == io.EOF { 33 r.cb(r.seen) 34 r.lastTime = now 35 } 36 return 37 }