52 lines
933 B
Go
52 lines
933 B
Go
// Copyright (C) 2022 Marius Schellenberger
|
|
|
|
package fs
|
|
|
|
import "sort"
|
|
|
|
type Chunk [2]int64
|
|
|
|
type Chunks []Chunk
|
|
|
|
func (cs Chunks) Len() int { return len(cs) }
|
|
func (cs Chunks) Less(i, j int) bool { return cs[i][0] < cs[j][0] }
|
|
func (cs Chunks) Swap(i, j int) { cs[i], cs[j] = cs[j], cs[i] }
|
|
|
|
func (cs Chunks) Exists(off int64, n int, size int64) bool {
|
|
end := off + int64(n)
|
|
if end > size {
|
|
end = size
|
|
}
|
|
for _, c := range cs {
|
|
if c[0] <= off && c[1] > off && c[1] >= end {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func (cs *Chunks) Add(off int64, n int) {
|
|
*cs = append(*cs, Chunk{off, off + int64(n)})
|
|
cs.merge()
|
|
}
|
|
|
|
func (cs *Chunks) merge() {
|
|
c := *cs
|
|
if len(c) < 2 {
|
|
return
|
|
}
|
|
sort.Sort(*cs)
|
|
for i := 0; i < len(c); i++ {
|
|
if i+1 == len(c) {
|
|
break
|
|
}
|
|
if c[i][1] >= c[i+1][0] {
|
|
if c[i+1][1] > c[i][1] {
|
|
c[i][1] = c[i+1][1]
|
|
}
|
|
c = append(c[:i+1], c[i+2:]...)
|
|
i--
|
|
}
|
|
}
|
|
*cs = c
|
|
}
|