...

Source file src/k8s.io/kubernetes/pkg/kubelet/util/ioutils/ioutils.go

Documentation: k8s.io/kubernetes/pkg/kubelet/util/ioutils

     1  /*
     2  Copyright 2016 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package ioutils
    18  
    19  import "io"
    20  
    21  // LimitWriter is a copy of the standard library ioutils.LimitReader,
    22  // applied to the writer interface.
    23  // LimitWriter returns a Writer that writes to w
    24  // but stops with EOF after n bytes.
    25  // The underlying implementation is a *LimitedWriter.
    26  func LimitWriter(w io.Writer, n int64) io.Writer { return &LimitedWriter{w, n} }
    27  
    28  // A LimitedWriter writes to W but limits the amount of
    29  // data returned to just N bytes. Each call to Write
    30  // updates N to reflect the new amount remaining.
    31  // Write returns EOF when N <= 0 or when the underlying W returns EOF.
    32  type LimitedWriter struct {
    33  	W io.Writer // underlying writer
    34  	N int64     // max bytes remaining
    35  }
    36  
    37  func (l *LimitedWriter) Write(p []byte) (n int, err error) {
    38  	if l.N <= 0 {
    39  		return 0, io.ErrShortWrite
    40  	}
    41  	truncated := false
    42  	if int64(len(p)) > l.N {
    43  		p = p[0:l.N]
    44  		truncated = true
    45  	}
    46  	n, err = l.W.Write(p)
    47  	l.N -= int64(n)
    48  	if err == nil && truncated {
    49  		err = io.ErrShortWrite
    50  	}
    51  	return
    52  }
    53  

View as plain text