| 1 |
// Copyright The Notary Project Authors. |
| 2 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
// you may not use this file except in compliance with the License. |
| 4 |
// You may obtain a copy of the License at |
| 5 |
// |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
// Package io provides a LimitWriter that writes to an underlying writer up to |
| 15 |
// a limit. |
| 16 |
|
| 17 |
package io |
| 18 |
|
| 19 |
import ( |
| 20 |
"errors" |
| 21 |
"io" |
| 22 |
) |
| 23 |
|
| 24 |
// ErrLimitExceeded is returned when the write limit is exceeded. |
| 25 |
var ErrLimitExceeded = errors.New("write limit exceeded") |
| 26 |
|
| 27 |
// LimitedWriter is a writer that writes to an underlying writer up to a limit. |
| 28 |
type LimitedWriter struct { |
| 29 |
W io.Writer // underlying writer |
| 30 |
N int64 // remaining bytes |
| 31 |
} |
| 32 |
|
| 33 |
// LimitWriter returns a new LimitWriter that writes to w. |
| 34 |
// |
| 35 |
// parameters: |
| 36 |
// w: the writer to write to |
| 37 |
// limit: the maximum number of bytes to write |
| 38 |
func LimitWriter(w io.Writer, limit int64) *LimitedWriter { |
| 39 |
return &LimitedWriter{W: w, N: limit} |
| 40 |
} |
| 41 |
|
| 42 |
// Write writes p to the underlying writer up to the limit. |
| 43 |
func (l *LimitedWriter) Write(p []byte) (int, error) { |
| 44 |
if l.N <= 0 { |
| 45 |
return 0, ErrLimitExceeded |
| 46 |
} |
| 47 |
if int64(len(p)) > l.N { |
| 48 |
p = p[:l.N] |
| 49 |
} |
| 50 |
n, err := l.W.Write(p) |
| 51 |
l.N -= int64(n) |
| 52 |
return n, err |
| 53 |
} |