Skip to content

Commit

Permalink
interp: Make binary also respect bits_format
Browse files Browse the repository at this point in the history
  • Loading branch information
wader committed May 17, 2023
1 parent 4335c30 commit b2c0e5f
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 21 deletions.
24 changes: 24 additions & 0 deletions pkg/interp/binary.go
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,30 @@ func (b Binary) JQValueToNumber() any {
func (b Binary) JQValueToString() any {
return b.JQValueToGoJQ()
}
func (b Binary) JQValueToGoJQEx(optsFn func() (*Options, error)) any {
br, err := b.toReader()
if err != nil {
return err
}

brC, err := bitio.CloneReaderAtSeeker(br)
if err != nil {
return err
}

opts, err := optsFn()
if err != nil {
return err
}

s, err := opts.BitsFormatFn(brC)
if err != nil {
return err
}

return s
}

func (b Binary) JQValueToGoJQ() any {
buf, err := b.toBytesBuffer(b.r)
if err != nil {
Expand Down
25 changes: 4 additions & 21 deletions pkg/interp/decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,7 @@ func makeDecodeValueOut(dv *decode.Value, kind decodeValueKind, out any) any {
},
},
decodeValueBase: decodeValueBase{dv: dv},
bitsFormat: true,
isRaw: true,
}
case bool:
return decodeValue{
Expand Down Expand Up @@ -599,7 +599,7 @@ var _ DecodeValue = decodeValue{}
type decodeValue struct {
gojq.JQValue
decodeValueBase
bitsFormat bool
isRaw bool
}

func (v decodeValue) JQValueKey(name string) any {
Expand All @@ -609,34 +609,17 @@ func (v decodeValue) JQValueHas(key any) any {
return valueHas(key, v.decodeValueBase.JQValueKey, v.JQValue.JQValueHas)
}
func (v decodeValue) JQValueToGoJQEx(optsFn func() (*Options, error)) any {
if !v.bitsFormat {
if !v.isRaw {
return v.JQValueToGoJQ()
}

bv, err := v.decodeValueBase.ToBinary()
if err != nil {
return err
}
br, err := bv.toReader()
if err != nil {
return err
}

brC, err := bitio.CloneReaderAtSeeker(br)
if err != nil {
return err
}

opts, err := optsFn()
if err != nil {
return err
}
return bv.JQValueToGoJQEx(optsFn)

s, err := opts.BitsFormatFn(brC)
if err != nil {
return err
}
return s
}

// decode value array
Expand Down
5 changes: 5 additions & 0 deletions pkg/interp/testdata/binary.fqtest
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ $ fq -d mp3 '.frames[0].audio_data | ("", "md5", "hex", "base64", "snippet") as
"0000000000"
"AAAAAAA="
"<5>AAAAAAA="
$ fq -o bits_format=hex -n '[1,2,3] | tobytes'
|00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f|0123456789abcdef|
0x0|01 02 03| |...| |.: raw bits 0x0-0x2.7 (3)
$ fq -o bits_format=hex -V -n '[1,2,3] | tobytes'
"010203"
$ fq -d mp3 -i . test.mp3
mp3> [1, 2, 3] | tobytes
|00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f|0123456789abcdef|
Expand Down

0 comments on commit b2c0e5f

Please sign in to comment.