limitedwriter.go 668 B

1234567891011121314151617181920212223242526272829303132
  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 LimitedWriter struct {
  12. writer io.Writer
  13. bucket *ratelimit.Bucket
  14. }
  15. func NewWriteLimiter(w io.Writer, b *ratelimit.Bucket) *LimitedWriter {
  16. return &LimitedWriter{
  17. writer: w,
  18. bucket: b,
  19. }
  20. }
  21. func (w *LimitedWriter) Write(buf []byte) (int, error) {
  22. if w.bucket != nil {
  23. w.bucket.Wait(int64(len(buf)))
  24. }
  25. return w.writer.Write(buf)
  26. }