/
chunk.go
58 lines (52 loc) · 1.26 KB
/
chunk.go
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
package ipapng
import (
"encoding/binary"
"errors"
"fmt"
"hash"
"io"
)
// Each chunk starts with a uint32 length (big endian), then 4 byte name,
// then data and finally the CRC32 of the chunk data.
type Chunk struct {
Length uint32 // chunk data length
CType string // chunk type
Data []byte // chunk data
Crc32 uint32 // CRC32 of chunk data
crc hash.Hash32
}
// Populate will read bytes from the reader and populate a chunk.
func (c *Chunk) Populate(r io.Reader) error {
// 4 byte
buf := make([]byte, 4)
// Read first four bytes == chunk length.
if _, err := io.ReadFull(r, buf); err != nil {
return err
}
// Convert bytes to int.
c.Length = binary.BigEndian.Uint32(buf)
if _, err := io.ReadFull(r, buf); err != nil {
return err
}
c.CType = string(buf)
c.crc.Reset()
c.crc.Write(buf)
// Read chunk data.
tmp := make([]byte, c.Length)
if _, err := io.ReadFull(r, tmp); err != nil {
return err
}
c.Data = tmp
c.crc.Write(c.Data)
// Read CRC32 hash
if _, err := io.ReadFull(r, buf); err != nil {
return err
}
c.Crc32 = binary.BigEndian.Uint32(buf)
sum32 := c.crc.Sum32()
if c.Crc32 != sum32 {
fmt.Printf("Crc32:%v, sum crc32:%v\n", c.Crc32, sum32)
return errors.New(fmt.Sprintf("invalid checksum CType:%v", c.CType))
}
return nil
}