Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions pkg/encryption/json_types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Copyright 2026 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.

package encryption

import (
"encoding/base64"
"encoding/json"
"fmt"
)

// ByteArray supports decoding either:
// - a JSON string (base64-encoded bytes), or
// - a JSON array of uint8 values (TiKV status API style).
type ByteArray []byte

func (b *ByteArray) UnmarshalJSON(data []byte) error {
if len(data) == 0 || string(data) == "null" {
*b = nil
return nil
}

switch data[0] {
case '"':
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
decoded, err := base64.StdEncoding.DecodeString(s)
if err != nil {
return err
}
*b = decoded
return nil
case '[':
var ints []int
if err := json.Unmarshal(data, &ints); err != nil {
return err
}
out := make([]byte, len(ints))
for i, v := range ints {
if v < 0 || v > 255 {
return fmt.Errorf("byte value out of range: %d", v)
}
out[i] = byte(v)
}
*b = out
return nil

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The logic for unmarshaling a JSON array of numbers can be simplified. Instead of unmarshaling into a slice of ints and then converting to []byte with manual range checks, you can unmarshal directly into a []byte (which is an alias for []uint8). The json package handles the conversion and range checking for you, making the code more concise and efficient.

                var bytes []byte
		if err := json.Unmarshal(data, &bytes); err != nil {
			return err
		}
		*b = bytes
		return nil

default:
return fmt.Errorf("unsupported JSON type for bytes: %s", string(data))
}
}
Loading
Loading