crlf.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package crlf
  14. import (
  15. "bytes"
  16. "io"
  17. )
  18. type crlfWriter struct {
  19. io.Writer
  20. }
  21. // NewCRLFWriter implements a CR/LF line ending writer used for normalizing
  22. // text for Windows platforms.
  23. func NewCRLFWriter(w io.Writer) io.Writer {
  24. return crlfWriter{w}
  25. }
  26. func (w crlfWriter) Write(b []byte) (n int, err error) {
  27. for i, written := 0, 0; ; {
  28. next := bytes.Index(b[i:], []byte("\n"))
  29. if next == -1 {
  30. n, err := w.Writer.Write(b[i:])
  31. return written + n, err
  32. }
  33. next = next + i
  34. n, err := w.Writer.Write(b[i:next])
  35. if err != nil {
  36. return written + n, err
  37. }
  38. written += n
  39. n, err = w.Writer.Write([]byte("\r\n"))
  40. if err != nil {
  41. if n > 1 {
  42. n = 1
  43. }
  44. return written + n, err
  45. }
  46. written += 1
  47. i = next + 1
  48. }
  49. }