kraken

Форк
0
/
cappedbuffer.go 
54 строки · 1.7 Кб
1
// Copyright (c) 2016-2019 Uber Technologies, Inc.
2
//
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
6
//
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
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.
14
package rwutil
15

16
import (
17
	"bytes"
18
	"fmt"
19
	"io"
20

21
	"github.com/aws/aws-sdk-go/aws"
22

23
	"github.com/uber/kraken/utils/memsize"
24
)
25

26
type exceededCapError error
27

28
// CappedBuffer is a buffer that returns errors if the buffer exceeds cap.
29
type CappedBuffer struct {
30
	capacity int64
31
	buffer   *aws.WriteAtBuffer
32
}
33

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{})}
37
}
38

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))))
44
	}
45
	return b.buffer.WriteAt(p, pos)
46
}
47

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)
52
	}
53
	return nil
54
}
55

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.