Skip to content

Commit

Permalink
Query marshal/unmarshal support
Browse files Browse the repository at this point in the history
  • Loading branch information
wader committed Jan 1, 2024
1 parent 9867dd1 commit f65497d
Show file tree
Hide file tree
Showing 3 changed files with 247 additions and 95 deletions.
80 changes: 79 additions & 1 deletion operator.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package gojq

import (
"encoding/json"
"fmt"
"math"
"math/big"
"strings"
Expand Down Expand Up @@ -37,6 +39,62 @@ const (
OpUpdateAlt
)

// String implements [fmt.Stringer].
func OperatorFromString(s string) Operator {
switch s {
case "|":
return OpPipe
case ",":
return OpComma
case "+":
return OpAdd
case "-":
return OpSub
case "*":
return OpMul
case "/":
return OpDiv
case "%":
return OpMod
case "==":
return OpEq
case "!=":
return OpNe
case ">":
return OpGt
case "<":
return OpLt
case ">=":
return OpGe
case "<=":
return OpLe
case "and":
return OpAnd
case "or":
return OpOr
case "//":
return OpAlt
case "=":
return OpAssign
case "|=":
return OpModify
case "+=":
return OpUpdateAdd
case "-=":
return OpUpdateSub
case "*=":
return OpUpdateMul
case "/=":
return OpUpdateDiv
case "%=":
return OpUpdateMod
case "//=":
return OpUpdateAlt
default:
return 0
}
}

// String implements [fmt.Stringer].
func (op Operator) String() string {
switch op {
Expand Down Expand Up @@ -89,7 +147,7 @@ func (op Operator) String() string {
case OpUpdateAlt:
return "//="
default:
panic(op)
return ""
}
}

Expand Down Expand Up @@ -207,6 +265,26 @@ func (op Operator) getFunc() string {
}
}

func (op Operator) MarshalJSON() ([]byte, error) {
if op == 0 {
return json.Marshal(nil)
}
return json.Marshal(op.String())
}

func (op *Operator) UnmarshalJSON(text []byte) error {
var s string
err := json.Unmarshal(text, &s)
if err != nil {
return err
}
*op = OperatorFromString(s)
if *op == 0 {
return fmt.Errorf("unknown operator %v", s)
}
return nil
}

func binopTypeSwitch(
l, r any,
callbackInts func(_, _ int) any,
Expand Down
Loading

0 comments on commit f65497d

Please sign in to comment.