File: alignwriter.go

package info (click to toggle)
golang-github-u-root-uio 0.0~git20240224.d2acac8-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 276 kB
  • sloc: sh: 25; makefile: 2
file content (34 lines) | stat: -rw-r--r-- 751 bytes parent folder | download | duplicates (5)
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
// Copyright 2019 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package uio

import (
	"bytes"
	"io"
)

// AlignWriter keeps track of how many bytes were written so the writer can be
// aligned at a future time.
type AlignWriter struct {
	W io.Writer
	N int
}

// Write writes to the underlying io.Writew.
func (w *AlignWriter) Write(b []byte) (int, error) {
	n, err := w.W.Write(b)
	w.N += n
	return n, err
}

// Align aligns the writer to the given number of bytes using the given pad
// value.
func (w *AlignWriter) Align(n int, pad byte) error {
	if w.N%n == 0 {
		return nil
	}
	_, err := w.Write(bytes.Repeat([]byte{pad}, n-w.N%n))
	return err
}