Skip to content

Commit 791e65d

Browse files
committed
refactor: improve compaction logic for AddObject
Previously, an add operation would simply append the data object to the end of the data section. If one or more object(s) had previously been deleted from the image, this could result in wasted space. Now, we trim the data section based on in-use objects before adding the new object. Update tests to reflect this new behaviour.
1 parent de30604 commit 791e65d

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed

pkg/sif/create.go

+17-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Copyright (c) 2018-2023, Sylabs Inc. All rights reserved.
1+
// Copyright (c) 2018-2024, Sylabs Inc. All rights reserved.
22
// Copyright (c) 2017, SingularityWare, LLC. All rights reserved.
33
// Copyright (c) 2017, Yannick Cote <yhcote@gmail.com> All rights reserved.
44
// This software is licensed under a 3-clause BSD license. Please consult the
@@ -55,6 +55,20 @@ func writeDataObjectAt(ws io.WriteSeeker, offsetUnaligned int64, di DescriptorIn
5555
return nil
5656
}
5757

58+
// calculatedDataSize calculates the size of the data section based on the in-use descriptors.
59+
func (f *FileImage) calculatedDataSize() int64 {
60+
dataEnd := f.DataOffset()
61+
62+
f.WithDescriptors(func(d Descriptor) bool {
63+
if objectEnd := d.Offset() + d.Size(); dataEnd < objectEnd {
64+
dataEnd = objectEnd
65+
}
66+
return false
67+
})
68+
69+
return dataEnd - f.DataOffset()
70+
}
71+
5872
var (
5973
errInsufficientCapacity = errors.New("insufficient descriptor capacity to add data object(s) to image")
6074
errPrimaryPartition = errors.New("image already contains a primary partition")
@@ -80,6 +94,8 @@ func (f *FileImage) writeDataObject(i int, di DescriptorInput, t time.Time) erro
8094
d := &f.rds[i]
8195
d.ID = uint32(i) + 1
8296

97+
f.h.DataSize = f.calculatedDataSize()
98+
8399
if err := writeDataObjectAt(f.rw, f.h.DataOffset+f.h.DataSize, di, t, d); err != nil {
84100
return err
85101
}
Binary file not shown.
Binary file not shown.

0 commit comments

Comments
 (0)