Skip to content

Commit

Permalink
Merge pull request #328 from tri-adam/refactor-zero
Browse files Browse the repository at this point in the history
refactor: simplify zero implementation
  • Loading branch information
tri-adam authored Sep 20, 2023
2 parents e1f38f0 + 59cf700 commit cac8e77
Showing 1 changed file with 21 additions and 27 deletions.
48 changes: 21 additions & 27 deletions pkg/sif/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -322,32 +322,6 @@ func CreateContainerAtPath(path string, opts ...CreateOpt) (*FileImage, error) {
return f, nil
}

func zeroData(fimg *FileImage, descr *rawDescriptor) error {
// first, move to data object offset
if _, err := fimg.rw.Seek(descr.Offset, io.SeekStart); err != nil {
return err
}

var zero [4096]byte
n := descr.Size
upbound := int64(4096)
for {
if n < 4096 {
upbound = n
}

if _, err := fimg.rw.Write(zero[:upbound]); err != nil {
return err
}
n -= 4096
if n <= 0 {
break
}
}

return nil
}

// addOpts accumulates object add options.
type addOpts struct {
t time.Time
Expand Down Expand Up @@ -429,6 +403,26 @@ func (f *FileImage) isLast(d *rawDescriptor) bool {
return isLast
}

// zeroReader is an io.Reader that returns a stream of zero-bytes.
type zeroReader struct{}

func (zeroReader) Read(b []byte) (int, error) {
for i := range b {
b[i] = 0
}
return len(b), nil
}

// zero overwrites the data object described by d with a stream of zero bytes.
func (f *FileImage) zero(d *rawDescriptor) error {
if _, err := f.rw.Seek(d.Offset, io.SeekStart); err != nil {
return err
}

_, err := io.CopyN(f.rw, zeroReader{}, d.Size)
return err
}

// truncateAt truncates f at the start of the padded data object described by d.
func (f *FileImage) truncateAt(d *rawDescriptor) error {
start := d.Offset + d.Size - d.SizeWithPadding
Expand Down Expand Up @@ -512,7 +506,7 @@ func (f *FileImage) DeleteObject(id uint32, opts ...DeleteOpt) error {
}

if do.zero {
if err := zeroData(f, d); err != nil {
if err := f.zero(d); err != nil {
return fmt.Errorf("%w", err)
}
}
Expand Down

0 comments on commit cac8e77

Please sign in to comment.