summaryrefslogtreecommitdiff
path: root/lib/jsonutil/hex_string.go
diff options
context:
space:
mode:
authorLuke Shumaker <lukeshu@lukeshu.com>2023-07-22 23:27:02 -0600
committerLuke Shumaker <lukeshu@lukeshu.com>2023-07-23 00:07:30 -0600
commit325178506187df037f9a85eb2e09100eb794f4f9 (patch)
tree4031d78531ffffd863ed3a08e405316a37adee1f /lib/jsonutil/hex_string.go
parentab268a66f3554976cc1ffac9dbf03c6ad2bcdf0c (diff)
Pull the json-hex-encoding from shortsum to jsonutil
Diffstat (limited to 'lib/jsonutil/hex_string.go')
-rw-r--r--lib/jsonutil/hex_string.go42
1 files changed, 42 insertions, 0 deletions
diff --git a/lib/jsonutil/hex_string.go b/lib/jsonutil/hex_string.go
new file mode 100644
index 0000000..06970ce
--- /dev/null
+++ b/lib/jsonutil/hex_string.go
@@ -0,0 +1,42 @@
+// Copyright (C) 2023 Luke Shumaker <lukeshu@lukeshu.com>
+//
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+// Package jsonutil provides utilities for implementing the interfaces
+// consumed by the "git.lukeshu.com/go/lowmemjson" package.
+package jsonutil
+
+import (
+ "io"
+
+ "git.lukeshu.com/go/lowmemjson"
+)
+
+func EncodeHexString[T ~[]byte | ~string](w io.Writer, str T) error {
+ const hextable = "0123456789abcdef"
+ var buf [2]byte
+ buf[0] = '"'
+ if _, err := w.Write(buf[:1]); err != nil {
+ return err
+ }
+ for i := 0; i < len(str); i++ {
+ buf[0] = hextable[str[i]>>4]
+ buf[1] = hextable[str[i]&0x0f]
+ if _, err := w.Write(buf[:]); err != nil {
+ return err
+ }
+ }
+ buf[0] = '"'
+ if _, err := w.Write(buf[:1]); err != nil {
+ return err
+ }
+ return nil
+}
+
+func DecodeHexString(r io.RuneScanner, dst io.ByteWriter) error {
+ dec := &hexDecoder{dst: dst}
+ if err := lowmemjson.DecodeString(r, dec); err != nil {
+ return err
+ }
+ return dec.Close()
+}