]> git.r.bdr.sh - rbdr/mobius/blame - hotline/file_header.go
Fix io.Reader implementations and wrap more errors
[rbdr/mobius] / hotline / file_header.go
CommitLineData
6988a057
JH
1package hotline
2
3import (
4 "encoding/binary"
9cf66aea 5 "io"
9c44621e 6 "slices"
6988a057
JH
7)
8
9type FileHeader struct {
9cf66aea
JH
10 Size [2]byte // Total size of FileHeader payload
11 Type [2]byte // 0 for file, 1 for dir
12 FilePath []byte // encoded file path
45ca5d60
JH
13
14 readOffset int // Internal offset to track read progress
6988a057
JH
15}
16
17func NewFileHeader(fileName string, isDir bool) FileHeader {
18 fh := FileHeader{
9cf66aea 19 Type: [2]byte{0x00, 0x00},
6988a057
JH
20 FilePath: EncodeFilePath(fileName),
21 }
22 if isDir {
9cf66aea 23 fh.Type = [2]byte{0x00, 0x01}
6988a057
JH
24 }
25
26 encodedPathLen := uint16(len(fh.FilePath) + len(fh.Type))
9cf66aea 27 binary.BigEndian.PutUint16(fh.Size[:], encodedPathLen)
6988a057
JH
28
29 return fh
30}
31
9cf66aea 32func (fh *FileHeader) Read(p []byte) (int, error) {
45ca5d60 33 buf := slices.Concat(
9cf66aea
JH
34 fh.Size[:],
35 fh.Type[:],
6988a057 36 fh.FilePath,
45ca5d60
JH
37 )
38
39 if fh.readOffset >= len(buf) {
40 return 0, io.EOF // All bytes have been read
41 }
42
43 n := copy(p, buf[fh.readOffset:])
44 fh.readOffset += n
45
46 return n, nil
6988a057 47}