limitedreader.go 676 B

123456789101112131415161718192021222324252627282930313233
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at http://mozilla.org/MPL/2.0/.
  6. package connections
  7. import (
  8. "io"
  9. "github.com/juju/ratelimit"
  10. )
  11. type LimitedReader struct {
  12. reader io.Reader
  13. bucket *ratelimit.Bucket
  14. }
  15. func NewReadLimiter(r io.Reader, b *ratelimit.Bucket) *LimitedReader {
  16. return &LimitedReader{
  17. reader: r,
  18. bucket: b,
  19. }
  20. }
  21. func (r *LimitedReader) Read(buf []byte) (int, error) {
  22. n, err := r.reader.Read(buf)
  23. if r.bucket != nil {
  24. r.bucket.Wait(int64(n))
  25. }
  26. return n, err
  27. }