tools

Miscellaneous software tools
git clone http://git.omkov.net/tools
Log | Tree | Refs | Download

AuthorJakob Wakeling <[email protected]>
Date2024-05-31 03:15:34
Commit5f634e16c3a5cd459a29095b8eb8d2f23a49b119
Parentd88ffe6239539c1dd6f52d02994316b10693dd72

Add CBOR to/from JSON conversion tool

Diffstat

M Makefile | 1 +
A src/cbor/go.mod | 7 +++++++
A src/cbor/go.sum | 4 ++++
A src/cbor/main.go | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

4 files changed, 85 insertions, 0 deletions

diff --git a/Makefile b/Makefile
index 18b0296..9f97603 100644
--- a/Makefile
+++ b/Makefile
@@ -2,6 +2,7 @@
 all: help
 
 build: ## Build the project
+	@go build -C ./src/cbor -o ../../bin/cbor .
 	@go build -C ./src/unixtime -o ../../bin/unixtime .
 
 test: ## Run unit tests
diff --git a/src/cbor/go.mod b/src/cbor/go.mod
new file mode 100644
index 0000000..a529f2b
--- /dev/null
+++ b/src/cbor/go.mod
@@ -0,0 +1,7 @@
+module cbor
+
+go 1.22
+
+require github.com/fxamacker/cbor/v2 v2.6.0
+
+require github.com/x448/float16 v0.8.4 // indirect
diff --git a/src/cbor/go.sum b/src/cbor/go.sum
new file mode 100644
index 0000000..a22e9e1
--- /dev/null
+++ b/src/cbor/go.sum
@@ -0,0 +1,4 @@
+github.com/fxamacker/cbor/v2 v2.6.0 h1:sU6J2usfADwWlYDAFhZBQ6TnLFBHxgesMrQfQgk1tWA=
+github.com/fxamacker/cbor/v2 v2.6.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ=
+github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
+github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
diff --git a/src/cbor/main.go b/src/cbor/main.go
new file mode 100644
index 0000000..7845816
--- /dev/null
+++ b/src/cbor/main.go
@@ -0,0 +1,73 @@
+package main
+
+import (
+	"encoding/json"
+	"flag"
+	"fmt"
+	"io"
+	"log"
+	"os"
+
+	"github.com/fxamacker/cbor/v2"
+)
+
+func main() {
+	flag.Parse()
+
+	var buf []byte
+	var err error
+
+	if len(flag.Args()) == 0 {
+		buf, err = io.ReadAll(os.Stdin)
+	} else {
+		buf, err = os.ReadFile(flag.Args()[0])
+	}
+
+	if err != nil {
+		log.Fatalln(err.Error())
+	}
+
+	var v any
+	if err := cbor.Unmarshal(buf, &v); err == nil {
+		/* Decode CBOR to JSON */
+		buf, err := json.MarshalIndent(fixKeys(v), "", "\t")
+		if err != nil {
+			log.Fatalln(err.Error())
+		}
+		os.Stdout.Write(buf)
+	} else if err := json.Unmarshal(buf, &v); err == nil {
+		/* Encode JSON to CBOR */
+		buf, err := cbor.Marshal(v)
+		if err != nil {
+			log.Fatalln(err.Error())
+		}
+		os.Stdout.Write(buf)
+	} else {
+		log.Fatalln(err.Error())
+	}
+}
+
+func fixKeys(v any) any {
+	switch v := v.(type) {
+	case map[any]any:
+		o := make(map[string]any, len(v))
+		for k, e := range v {
+			o[fmt.Sprintf("%v", k)] = fixKeys(e)
+		}
+		return o
+	case []any:
+		o := make([]any, len(v))
+		for i, e := range v {
+			o[i] = fixKeys(e)
+		}
+		return o
+	}
+	return v
+}
+
+func If[T any](cond bool, a, b T) T {
+	if cond {
+		return a
+	}
+	return b
+}