github.com/timstclair/heapster@v0.20.0-alpha1/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/limitwriter/limitwriter.go (about) 1 /* 2 Copyright 2015 The Kubernetes Authors All rights reserved. 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 limitwriter 18 19 import ( 20 "errors" 21 "io" 22 ) 23 24 // New creates a writer that is limited to writing at most n bytes to w. This writer is not 25 // thread safe. 26 func New(w io.Writer, n int64) io.Writer { 27 return &limitWriter{ 28 w: w, 29 n: n, 30 } 31 } 32 33 // ErrMaximumWrite is returned when all bytes have been written. 34 var ErrMaximumWrite = errors.New("maximum write") 35 36 type limitWriter struct { 37 w io.Writer 38 n int64 39 } 40 41 func (w *limitWriter) Write(p []byte) (n int, err error) { 42 if int64(len(p)) > w.n { 43 p = p[:w.n] 44 } 45 if len(p) > 0 { 46 n, err = w.w.Write(p) 47 w.n -= int64(n) 48 } 49 if w.n == 0 { 50 err = ErrMaximumWrite 51 } 52 return 53 }