Skip to content

Commit

Permalink
fix: optimize use of tuples
Browse files Browse the repository at this point in the history
Signed-off-by: Dr. Carsten Leue <carsten.leue@de.ibm.com>
  • Loading branch information
CarstenLeue committed Feb 8, 2024
1 parent 79652d8 commit 9f6b6d4
Show file tree
Hide file tree
Showing 3 changed files with 658 additions and 1,084 deletions.
40 changes: 7 additions & 33 deletions cli/tuple.go
Original file line number Diff line number Diff line change
Expand Up @@ -405,8 +405,6 @@ func generateTupleHelpers(filename string, count int) error {

fmt.Fprintf(f, `
import (
"fmt"
"encoding/json"
M "github.com/IBM/fp-go/monoid"
O "github.com/IBM/fp-go/ord"
)
Expand Down Expand Up @@ -457,15 +455,15 @@ func generateTupleMarshal(f *os.File, i int) {
fmt.Fprintf(f, "func (t ")
writeTupleType(f, "T", i)
fmt.Fprintf(f, ") MarshalJSON() ([]byte, error) {\n")
fmt.Fprintf(f, " return json.Marshal([]any{")
fmt.Fprintf(f, " return tupleMarshalJSON(")
// function prototypes
for j := 1; j <= i; j++ {
if j > 1 {
fmt.Fprintf(f, ", ")
}
fmt.Fprintf(f, "t.F%d", j)
}
fmt.Fprintf(f, "})\n")
fmt.Fprintf(f, ")\n")
fmt.Fprintf(f, "}\n")
}

Expand All @@ -475,19 +473,12 @@ func generateTupleUnmarshal(f *os.File, i int) {
fmt.Fprintf(f, "func (t *")
writeTupleType(f, "T", i)
fmt.Fprintf(f, ") UnmarshalJSON(data []byte) error {\n")
fmt.Fprintf(f, " var tmp []json.RawMessage\n")
fmt.Fprintf(f, " if err := json.Unmarshal(data, &tmp); err != nil {return err}\n")
fmt.Fprintf(f, " l := len(tmp)\n")
// unmarshal fields
for j := 1; j <= i; j++ {
fmt.Fprintf(f, " if l > %d {\n", j-1)
fmt.Fprintf(f, " if err := json.Unmarshal(tmp[%d], &t.F%d); err != nil {return err}\n", j-1, j)
}
fmt.Fprintf(f, " ")
fmt.Fprintf(f, " return tupleUnmarshalJSON(data")
// function prototypes
for j := 1; j <= i; j++ {
fmt.Fprintf(f, "}")
fmt.Fprintf(f, ", &t.F%d", j)
}
fmt.Fprintf(f, "\n return nil\n")
fmt.Fprintf(f, ")\n")
fmt.Fprintf(f, "}\n")
}

Expand Down Expand Up @@ -570,30 +561,13 @@ func generateTupleString(f *os.File, i int) {
writeTupleType(f, "T", i)
fmt.Fprintf(f, ") String() string {\n")
// convert to string
fmt.Fprintf(f, " return fmt.Sprintf(\"Tuple%d[", i)
for j := 1; j <= i; j++ {
if j > 1 {
fmt.Fprintf(f, ", ")
}
fmt.Fprintf(f, "%s", "%T")
}
fmt.Fprintf(f, "](")
for j := 1; j <= i; j++ {
if j > 1 {
fmt.Fprintf(f, ", ")
}
fmt.Fprintf(f, "%s", "%v")
}
fmt.Fprintf(f, ")\", ")
fmt.Fprint(f, " return tupleString(")
for j := 1; j <= i; j++ {
if j > 1 {
fmt.Fprintf(f, ", ")
}
fmt.Fprintf(f, "t.F%d", j)
}
for j := 1; j <= i; j++ {
fmt.Fprintf(f, ", t.F%d", j)
}
fmt.Fprintf(f, ")\n")
fmt.Fprintf(f, "}\n")
}
Expand Down

0 comments on commit 9f6b6d4

Please sign in to comment.