The scanner can be used to read any BSR data file. When creating a new scanner, it will first verify the BSR magic string. Individual Chunks can then be read back by calling Scan. The scanner will compute a sha256sum while it is reading chunks. If the scanner was created using the WithSha256Sum option, it will compare the computed checksum with the one provided via the option once the scanner encounters an end chunk (DONE) or an io.EOF error from the reader. If the checksums do not match, and error will be returned from Scan. The current sha256sum can be returned from the scanner using the Sum method. There is also a convenience function, ChunkWalk that can be used to call a function on each Chunk returned by a scanner.
51 lines
1.1 KiB
Go
51 lines
1.1 KiB
Go
// Copyright (c) HashiCorp, Inc.
|
|
// SPDX-License-Identifier: MPL-2.0
|
|
|
|
package bsr
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
|
|
"github.com/hashicorp/boundary/internal/bsr/internal/is"
|
|
)
|
|
|
|
const (
|
|
// Magic is the magic string / magic number / file signature used to
|
|
// identify a BSR data file.
|
|
//
|
|
// See: https://en.wikipedia.org/wiki/File_format#Magic_number
|
|
Magic magic = magic("\x89BSR\r\n\x1a\n")
|
|
|
|
magicSize = len(Magic)
|
|
)
|
|
|
|
type magic string
|
|
|
|
// Bytes returns the magic as a []byte.
|
|
func (s magic) Bytes() []byte {
|
|
return []byte(s)
|
|
}
|
|
|
|
// ReadMagic attempts to read the magic string from the given io.Reader.
|
|
// If it is unable to read enough bytes, or if the magic string does not match
|
|
// an error is returned.
|
|
func ReadMagic(r io.Reader) error {
|
|
const op = "bsr.ReadMagic"
|
|
|
|
if is.Nil(r) {
|
|
return fmt.Errorf("%s: reader is nil: %w", op, ErrInvalidParameter)
|
|
}
|
|
|
|
m := make([]byte, magicSize)
|
|
_, err := io.ReadAtLeast(r, m, magicSize)
|
|
if err != nil {
|
|
return fmt.Errorf("%s: %w", op, err)
|
|
}
|
|
|
|
if len(m) < magicSize || magic(m[:magicSize]) != Magic {
|
|
return fmt.Errorf("%s: %w", op, ErrInvalidMagic)
|
|
}
|
|
return nil
|
|
}
|