-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathallocsizechecker.go
More file actions
74 lines (65 loc) · 2.16 KB
/
allocsizechecker.go
File metadata and controls
74 lines (65 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package pkg
import (
"math"
"math/bits"
)
type AllocSizeChecker struct {
// allocatedSize tracks the total allocated size in bytes since last resetAllocSize call.
// Normally used by Allocator. This tracking is independent of the Allocator's calls
// to Alloc(), which DO NOT result in allocatedSize being updated automatically.
allocatedSize uint
}
// ResetAllocSize resets the allocated size counter to zero.
func (a *AllocSizeChecker) ResetAllocSize() {
a.allocatedSize = 0
}
// AddAllocSize adds the size to the allocated size counter.
func (a *AllocSizeChecker) AddAllocSize(size uint) {
var carry uint
a.allocatedSize, carry = bits.Add(a.allocatedSize, size, 0)
if carry != 0 {
// Overflow, saturate to max value.
a.allocatedSize = math.MaxUint
}
}
// IsOverLimit checks if the allocated size exceeds the allocation limit.
func (a *AllocSizeChecker) IsOverLimit() bool {
return a.allocatedSize > RecordAllocLimit
}
// PrepAllocSize checks if allocating size bytes would exceed the allocation limit.
// It adds the size to the total allocated so far.
// Returns ErrRecordAllocLimitExceeded if the limit is exceeded.
func (a *AllocSizeChecker) PrepAllocSize(size uint) error {
var carry uint
a.allocatedSize, carry = bits.Add(a.allocatedSize, size, 0)
if carry != 0 {
// Overflow, saturate to max value.
a.allocatedSize = math.MaxUint
return ErrRecordAllocLimitExceeded
}
if a.IsOverLimit() {
return ErrRecordAllocLimitExceeded
}
return nil
}
// PrepAllocSizeN checks if allocating size*count bytes would exceed the allocation limit.
// It adds the size*count to the total allocated so far.
// Returns ErrRecordAllocLimitExceeded if the limit is exceeded.
func (a *AllocSizeChecker) PrepAllocSizeN(size uint, count uint) error {
carry, totalSize := bits.Mul(size, count)
if carry != 0 {
// Overflow, saturate to max value.
a.allocatedSize = math.MaxUint
return ErrRecordAllocLimitExceeded
}
a.allocatedSize, carry = bits.Add(a.allocatedSize, totalSize, 0)
if carry != 0 {
// Overflow, saturate to max value.
a.allocatedSize = math.MaxUint
return ErrRecordAllocLimitExceeded
}
if a.IsOverLimit() {
return ErrRecordAllocLimitExceeded
}
return nil
}