disk: add alignment helper

Add a utility method that can be used to align data to the next "grain"
which is currently defined as 1 MiB -- the default used by sfdisk.

Add corresponding tests.
This commit is contained in:
Christian Kellner 2021-12-20 19:26:53 +01:00 committed by Tom Gundersen
parent b7abef54e8
commit 930633c249
2 changed files with 30 additions and 0 deletions

View file

@ -19,6 +19,8 @@ import (
const (
// Default sector size in bytes
DefaultSectorSize = 512
DefaultGrainBytes = uint64(1024 * 1024) // 1 MiB
)
type PartitionTable struct {
@ -58,6 +60,14 @@ type Filesystem struct {
FSTabPassNo uint64
}
// AlignUp will align the given sectors to next aligned sector
func (pt *PartitionTable) AlignUp(sectors uint64) uint64 {
grain := pt.BytesToSectors(DefaultGrainBytes)
return ((sectors + grain) / grain) * grain
}
// Convert the given bytes to the number of sectors.
func (pt *PartitionTable) BytesToSectors(size uint64) uint64 {
sectorSize := pt.SectorSize

View file

@ -9,6 +9,26 @@ import (
"github.com/stretchr/testify/assert"
)
func TestDisk_AlignUp(t *testing.T) {
pt := disk.PartitionTable{}
firstAligned := pt.BytesToSectors(disk.DefaultGrainBytes)
tests := []struct {
size uint64
want uint64
}{
{0, firstAligned},
{1, firstAligned},
{firstAligned - 1, firstAligned},
}
for _, tt := range tests {
got := pt.AlignUp(tt.size)
assert.Equal(t, tt.want, got)
}
}
func TestDisk_DynamicallyResizePartitionTable(t *testing.T) {
mountpoints := []blueprint.FilesystemCustomization{
{