testutil.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright (C) 2019 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 https://mozilla.org/MPL/2.0/.
  6. package testutil
  7. import (
  8. "errors"
  9. "sync"
  10. )
  11. var ErrClosed = errors.New("closed")
  12. // BlockingRW implements io.Reader, Writer and Closer, but only returns when closed
  13. type BlockingRW struct {
  14. c chan struct{}
  15. closeOnce sync.Once
  16. }
  17. func NewBlockingRW() *BlockingRW {
  18. return &BlockingRW{
  19. c: make(chan struct{}),
  20. closeOnce: sync.Once{},
  21. }
  22. }
  23. func (rw *BlockingRW) Read(_ []byte) (int, error) {
  24. <-rw.c
  25. return 0, ErrClosed
  26. }
  27. func (rw *BlockingRW) Write(_ []byte) (int, error) {
  28. <-rw.c
  29. return 0, ErrClosed
  30. }
  31. func (rw *BlockingRW) Close() error {
  32. rw.closeOnce.Do(func() {
  33. close(rw.c)
  34. })
  35. return nil
  36. }
  37. // NoopRW implements io.Reader and Writer but never returns when called
  38. type NoopRW struct{}
  39. func (*NoopRW) Read(p []byte) (n int, err error) {
  40. return len(p), nil
  41. }
  42. func (*NoopRW) Write(p []byte) (n int, err error) {
  43. return len(p), nil
  44. }
  45. type NoopCloser struct{}
  46. func (NoopCloser) Close() error {
  47. return nil
  48. }