-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheader.go
More file actions
63 lines (57 loc) · 1.76 KB
/
header.go
File metadata and controls
63 lines (57 loc) · 1.76 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package xtx
import (
"encoding/binary"
"fmt"
"io"
)
// Header represents the 22-byte image header shared by XTG and XTH formats.
type Header struct {
Mark uint32 // File identifier (MagicXTG or MagicXTH)
Width uint16 // Image width in pixels
Height uint16 // Image height in pixels
ColorMode uint8 // Color mode (0 = monochrome)
Compression uint8 // Compression (0 = uncompressed)
DataSize uint32 // Image data size in bytes
MD5 uint64 // Truncated MD5 checksum (first 8 bytes); 0 = unused
}
// WriteTo writes the header in little-endian binary format to w.
func (h *Header) WriteTo(w io.Writer) (int64, error) {
err := binary.Write(w, binary.LittleEndian, h)
if err != nil {
return 0, fmt.Errorf("xtx: writing header: %w", err)
}
return HeaderSize, nil
}
// ReadFrom reads the header in little-endian binary format from r.
func (h *Header) ReadFrom(r io.Reader) (int64, error) {
err := binary.Read(r, binary.LittleEndian, h)
if err != nil {
return 0, fmt.Errorf("xtx: reading header: %w", err)
}
return HeaderSize, nil
}
// Validate checks the header for consistency and returns an error if invalid.
func (h *Header) Validate() error {
if h.Mark != MagicXTG && h.Mark != MagicXTH {
return ErrInvalidMagic
}
if h.Width == 0 || h.Height == 0 {
return ErrDimensionZero
}
if h.Compression != 0 {
return ErrUnsupportedCompression
}
var expected uint32
if h.Mark == MagicXTG {
expected = uint32((int(h.Width)+7)/8) * uint32(h.Height)
} else {
// Column-major layout: each column has (height+7)/8 bytes per plane.
// Total = width * colBytes * 2 planes.
colBytes := uint32((int(h.Height) + 7) / 8)
expected = uint32(h.Width) * colBytes * 2
}
if h.DataSize != expected {
return ErrDataSizeMismatch
}
return nil
}