commit cb9f53840ce84710f2da783c0f4efc3a96479ba2
parent 7c79b0547941d5c8539ca8c8206cefdf0f4f74aa
Author: Oliver Lowe <o@olowe.co>
Date: Sat, 17 Aug 2024 10:41:03 +1000
mpegts: let callers handle packet length errors explicitly
Diffstat:
1 file changed, 8 insertions(+), 2 deletions(-)
diff --git a/mpegts/codec.go b/mpegts/codec.go
@@ -2,10 +2,14 @@ package mpegts
import (
"encoding/binary"
+ "errors"
"fmt"
"io"
)
+var ErrLongPacket = errors.New("long packet")
+var ErrShortPacket = errors.New("short packet")
+
func Unmarshal(buf []byte, p *Packet) error {
if len(buf) != PacketSize {
return fmt.Errorf("need exactly %d bytes, have %d", PacketSize, len(buf))
@@ -253,8 +257,10 @@ func Encode(w io.Writer, p *Packet) error {
if p.Payload != nil {
buf = append(buf, p.Payload...)
}
- if len(buf) != PacketSize {
- return fmt.Errorf("bad encoded packet length %d", len(buf))
+ if len(buf) > PacketSize {
+ return fmt.Errorf("%w: %d bytes", ErrLongPacket, len(buf))
+ } else if len(buf) < PacketSize {
+ return fmt.Errorf("%w: %d bytes", ErrShortPacket, len(buf))
}
_, err := w.Write(buf)
return err