meowlib/buffer.go

67 lines
1.3 KiB
Go
Raw Permalink Normal View History

2022-11-29 22:19:54 +01:00
package meowlib
import (
"errors"
"strconv"
)
func min(a, b int) int {
if a <= b {
return a
}
return b
}
func BufferSplit(buffer []byte, parts uint8) (packets [][]byte, err error) {
if int(parts) > len(buffer) {
return nil, errors.New("too many parts(" + strconv.Itoa(int(parts)) + ") for buffer len(" + strconv.Itoa(len(buffer)) + ")")
}
chunksize := int(len(buffer)/int(parts)) + 1
packets = make([][]byte, parts)
for c := 0; c < int(parts); c++ {
if c == 0 {
packets[c] = []byte{byte(c), byte(parts)}
} else {
packets[c] = []byte{byte(c)}
}
}
chunk := 0
for i := 0; i < len(buffer); i += chunksize {
batch := buffer[i:min(i+chunksize, len(buffer))]
packets[chunk] = append(packets[chunk], batch...)
chunk++
}
return packets, nil
}
func BufferMerge(packets [][]byte) (buffer []byte, err error) {
var parts int
found := false
buffer = []byte{}
for _, b := range packets {
if b[0] == 0 {
parts = int(b[1])
buffer = append(buffer, b[2:]...)
found = true
break
}
}
if !found {
return nil, errors.New("start packet not found")
}
for i := 1; i < parts; i++ {
found = false
for _, b := range packets {
if b[0] == byte(i) {
buffer = append(buffer, b[1:]...)
found = true
break
}
}
if !found {
return nil, errors.New("packet #" + strconv.Itoa(i) + " not found")
}
}
return buffer, nil
}