replacingwriter.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This program is free software: you can redistribute it and/or modify it
  4. // under the terms of the GNU General Public License as published by the Free
  5. // Software Foundation, either version 3 of the License, or (at your option)
  6. // any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful, but WITHOUT
  9. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  11. // more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program. If not, see <http://www.gnu.org/licenses/>.
  15. package osutil
  16. import (
  17. "bytes"
  18. "io"
  19. )
  20. type ReplacingWriter struct {
  21. Writer io.Writer
  22. From byte
  23. To []byte
  24. }
  25. func (w ReplacingWriter) Write(bs []byte) (int, error) {
  26. var n, written int
  27. var err error
  28. newlineIdx := bytes.IndexByte(bs, w.From)
  29. for newlineIdx >= 0 {
  30. n, err = w.Writer.Write(bs[:newlineIdx])
  31. written += n
  32. if err != nil {
  33. break
  34. }
  35. if len(w.To) > 0 {
  36. n, err := w.Writer.Write(w.To)
  37. if n == len(w.To) {
  38. written++
  39. }
  40. if err != nil {
  41. break
  42. }
  43. }
  44. bs = bs[newlineIdx+1:]
  45. newlineIdx = bytes.IndexByte(bs, w.From)
  46. }
  47. n, err = w.Writer.Write(bs)
  48. written += n
  49. return written, err
  50. }