1
// Copyright (c) 2016-2019 Uber Technologies, Inc.
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
7
// http://www.apache.org/licenses/LICENSE-2.0
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
21
"github.com/aws/aws-sdk-go/aws"
23
"github.com/uber/kraken/utils/memsize"
26
type exceededCapError error
28
// CappedBuffer is a buffer that returns errors if the buffer exceeds cap.
29
type CappedBuffer struct {
31
buffer *aws.WriteAtBuffer
34
// NewCappedBuffer creates a new CappedBuffer with the given capacity
35
func NewCappedBuffer(capacity int) *CappedBuffer {
36
return &CappedBuffer{capacity: int64(capacity), buffer: aws.NewWriteAtBuffer([]byte{})}
39
// WriteAt writes the slice of bytes into CappedBuffer at given position
40
func (b *CappedBuffer) WriteAt(p []byte, pos int64) (n int, err error) {
41
if pos+int64(len(p)) > b.capacity {
42
return 0, exceededCapError(
43
fmt.Errorf("buffer exceed max capacity %s", memsize.Format(uint64(b.capacity))))
45
return b.buffer.WriteAt(p, pos)
48
// DrainInto copies/drains/empties contents of CappedBuffer into dst
49
func (b *CappedBuffer) DrainInto(dst io.Writer) error {
50
if _, err := io.Copy(dst, bytes.NewReader(b.buffer.Bytes())); err != nil {
51
return fmt.Errorf("drain buffer: %s", err)