This repository has been archived by the owner on Jul 27, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
allocator.go
107 lines (90 loc) · 1.95 KB
/
allocator.go
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package sbs
import (
"encoding/binary"
"fmt"
"github.com/ipfs/go-sbs/consts"
)
var ErrAllocatorFull = fmt.Errorf("allocator full")
const (
FlagFragmented = 1 << iota
)
type AllocatorBlock struct {
Version int
InUse uint64
LastAllocator uint64
Offset uint64
Flag byte
FreeBlocks int
FreeBlockList []int
Bitfield []byte
buf []byte
}
func readInt24(buf []byte) uint64 {
return uint64(buf[2]) + uint64(buf[1])<<8 + uint64(buf[0])<<16
}
func writeInt24(buf []byte, v uint64) {
buf[2] = byte(v) & 0xff
buf[1] = byte(v>>8) & 0xff
buf[0] = byte(v>>16) & 0xff
}
func InitAllocator(buf []byte) {
buf[0] = 1
buf[1] = 0
buf[2] = 0
buf[3] = 1
}
func LoadAllocator(buf []byte) (*AllocatorBlock, error) {
a := new(AllocatorBlock)
a.Version = int(buf[0])
a.Bitfield = buf[64:]
if a.Version != 1 {
InitAllocator(buf)
a.SetBit(0)
}
a.InUse = readInt24(buf[1:4])
a.LastAllocator = binary.BigEndian.Uint64(buf[4:12])
a.buf = buf
return a, nil
}
func (a *AllocatorBlock) SetBit(i uint64) error {
ix := i / 8
pos := uint(i % 8)
a.Bitfield[ix] = a.Bitfield[ix] | (1 << pos)
return nil
}
func (a *AllocatorBlock) ClearBit(i uint64) error {
ix := i / 8
pos := uint(i % 8)
a.Bitfield[ix] &^= (1 << pos)
return nil
}
func (a *AllocatorBlock) Allocate(n uint64) ([]uint64, error) {
if a.Flag&FlagFragmented != 0 {
panic("cant handle fragmented allocation yet")
}
if a.InUse == consts.BlocksPerAllocator {
return nil, ErrAllocatorFull
}
var errFinal error
if n > consts.BlocksPerAllocator-a.InUse {
n = consts.BlocksPerAllocator - a.InUse
errFinal = ErrAllocatorFull
}
var out []uint64
for i := a.InUse; i < a.InUse+n; i++ {
err := a.SetBit(i)
if err != nil {
return nil, err
}
out = append(out, i+a.Offset)
}
a.InUse += n
writeInt24(a.buf[1:4], a.InUse)
return out, errFinal
}
func (a *AllocatorBlock) Free(blks []uint64) error {
for _, b := range blks {
a.ClearBit(b)
}
return nil
}