dc4bc/qr/chunk.go

61 lines
1.3 KiB
Go
Raw Normal View History

2020-09-01 08:06:37 -07:00
package qr
import (
"bytes"
"encoding/gob"
"fmt"
"math"
)
type chunk struct {
2020-09-29 08:16:20 -07:00
Data []byte
Index uint
Total uint
2020-09-01 08:06:37 -07:00
}
2020-09-22 06:15:18 -07:00
// DataToChunks divides a data on chunks with a size chunkSize
2020-09-29 08:16:20 -07:00
func DataToChunks(data []byte, chunkSize int) ([][]byte, error) {
chunksCount := int(math.Ceil(float64(len(data)) / float64(chunkSize)))
2020-09-01 08:06:37 -07:00
chunks := make([][]byte, 0, chunksCount)
2020-09-29 08:16:20 -07:00
index := uint(0)
2020-09-01 08:06:37 -07:00
for offset := 0; offset < len(data); offset += chunkSize {
offsetEnd := offset + chunkSize
if offsetEnd > len(data) {
offsetEnd = len(data)
}
chunkBz, err := encodeChunk(chunk{
2020-09-29 08:16:20 -07:00
Data: data[offset:offsetEnd],
Total: uint(chunksCount),
Index: index,
2020-09-01 08:06:37 -07:00
})
if err != nil {
return nil, fmt.Errorf("failed to encode chunk: %w", err)
}
chunks = append(chunks, chunkBz)
2020-09-29 08:16:20 -07:00
index++
2020-09-01 08:06:37 -07:00
}
return chunks, nil
}
func decodeChunk(data []byte) (*chunk, error) {
var (
c chunk
err error
)
dec := gob.NewDecoder(bytes.NewBuffer(data))
if err = dec.Decode(&c); err != nil {
return nil, fmt.Errorf("failed to decode chunk: %w", err)
}
return &c, nil
}
func encodeChunk(c chunk) ([]byte, error) {
buf := bytes.NewBuffer(nil)
enc := gob.NewEncoder(buf)
if err := enc.Encode(c); err != nil {
return nil, fmt.Errorf("failed to encode chunk: %w", err)
}
return buf.Bytes(), nil
}