summaryrefslogtreecommitdiff
path: root/lib/jsonutil/hex_decoder.go
diff options
context:
space:
mode:
authorLuke Shumaker <lukeshu@lukeshu.com>2023-07-23 00:46:42 -0600
committerLuke Shumaker <lukeshu@lukeshu.com>2023-07-23 00:46:42 -0600
commitc57cc3d4739ffa0346350c63fb4ec59a63b56e46 (patch)
tree8d22d276e869e5b816e3113def16b3defcbd538c /lib/jsonutil/hex_decoder.go
parent77628ce11ce3693d8ac06f1a404a1005ba05f190 (diff)
parent6e104326f81ec59ece1817988af41b70e4f4cd15 (diff)
Merge branch 'lukeshu/json'
Diffstat (limited to 'lib/jsonutil/hex_decoder.go')
-rw-r--r--lib/jsonutil/hex_decoder.go61
1 files changed, 61 insertions, 0 deletions
diff --git a/lib/jsonutil/hex_decoder.go b/lib/jsonutil/hex_decoder.go
new file mode 100644
index 0000000..e5c84a7
--- /dev/null
+++ b/lib/jsonutil/hex_decoder.go
@@ -0,0 +1,61 @@
+// Copyright (C) 2023 Luke Shumaker <lukeshu@lukeshu.com>
+//
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+package jsonutil
+
+import (
+ "fmt"
+ "io"
+ "math"
+)
+
+type invalidHexRuneError rune
+
+func (e invalidHexRuneError) Error() string {
+ return fmt.Sprintf("jsonutil: invalid hex digit: %q", rune(e))
+}
+
+// hexDecoder is like an encoding/hex.Decoder, but has a "push"
+// interface rather than a "pull" interface.
+type hexDecoder struct {
+ dst io.ByteWriter
+
+ buf byte
+ bufOK bool
+}
+
+func (d *hexDecoder) WriteRune(r rune) (int, error) {
+ if r > math.MaxUint8 {
+ return 0, invalidHexRuneError(r)
+ }
+
+ c := byte(r)
+ var v byte
+ //nolint:gomnd // Hex conversion.
+ switch {
+ case '0' <= c && c <= '9':
+ v = c - '0'
+ case 'a' <= c && c <= 'f':
+ v = c - 'a' + 10
+ case 'A' <= c && c <= 'F':
+ v = c - 'A' + 10
+ default:
+ return 0, invalidHexRuneError(r)
+ }
+
+ if !d.bufOK {
+ d.buf = v
+ d.bufOK = true
+ return 1, nil
+ }
+ d.bufOK = false
+ return 1, d.dst.WriteByte(d.buf<<4 | v)
+}
+
+func (d *hexDecoder) Close() error {
+ if d.bufOK {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}