github.com/cloudbase/juju-core@v0.0.0-20140504232958-a7271ac7912f/environs/sshstorage/linewrapwriter.go (about)

     1  // Copyright 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package sshstorage
     5  
     6  import (
     7  	"io"
     8  )
     9  
    10  type lineWrapWriter struct {
    11  	out    io.Writer
    12  	remain int
    13  	max    int
    14  }
    15  
    16  // NewLineWrapWriter returns an io.Writer that encloses the given
    17  // io.Writer, wrapping lines at the the specified line length.
    18  // It will panic if the line length is not positive.
    19  //
    20  // Note: there is no special consideration for input that
    21  // already contains newlines; this will simply add newlines
    22  // after every "lineLength" bytes. Moreover it gives no
    23  // consideration to multibyte utf-8 characters, which it can split
    24  // arbitrarily.
    25  //
    26  // This is currently only appropriate for wrapping base64-encoded
    27  // data, which is why it lives here.
    28  func newLineWrapWriter(out io.Writer, lineLength int) io.Writer {
    29  	if lineLength <= 0 {
    30  		panic("lineWrapWriter with line length <= 0")
    31  	}
    32  	return &lineWrapWriter{
    33  		out:    out,
    34  		remain: lineLength,
    35  		max:    lineLength,
    36  	}
    37  }
    38  
    39  func (w *lineWrapWriter) Write(buf []byte) (int, error) {
    40  	total := 0
    41  	for len(buf) >= w.remain {
    42  		n, err := w.out.Write(buf[0:w.remain])
    43  		w.remain -= n
    44  		total += n
    45  		if err != nil {
    46  			return total, err
    47  		}
    48  		if _, err := w.out.Write([]byte("\n")); err != nil {
    49  			return total, err
    50  		}
    51  		w.remain = w.max
    52  		buf = buf[n:]
    53  	}
    54  	n, err := w.out.Write(buf)
    55  	w.remain -= n
    56  	return total + n, err
    57  }