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