codec/h264/h264dec: FieldReader helper type

Issue #117 resolved
Saxon Milton created an issue

As per @kortschak 's suggestion regarding parsing related calls to ReadBits, we should have a helper type that will hold a sticky error. The type will offer methods for reading specific field types like bool and int. These functions that will wrap calls to bits.BitReader.ReadBits and will also check the current error before doing anything… if non nil, the function will return immediately. If not nil, we continue with reading. If the read results in an err, the err is updated. At the end of the series of read calls, we check the err and return.

The type might look like this:

type FieldReader struct {
  err error
  br *bits.BitReader
}

func (r FieldReader) ReadBool() bool {
  if err != nil {
    return
  }

  b, r.err := br.ReadBits(1)
  return b == 1
}

func (r FieldReader) ReadBitsInt(n int) bool {
  if err != nil {
    return
  }

  b, r.err := br.ReadBits(n)
  return int(b)
}

func (r FieldReader) Err() error {
  return err
}

A parsing function might look like this,

func ParseSyntaxStructure(br *bits.BitReader) (*SyntaxStructure, error) {
  s := &SyntaxStructure{}
  r := FieldReader{br:br}

  s.Field1 = r.ReadBool()
  s.Field2 = r.ReadBool()
  s.Field3 = r.ReadBitsInt(3)

  err := r.Err()
  if err != nil {
    return nil, err
  }
  return s, nil
}

Comments (3)

  1. Log in to comment