forked from cosmos/cosmos-sdk
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(collections): add
NewJSONValueCodec
(cosmos#19861)
Co-authored-by: Facundo Medica <[email protected]> Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
- Loading branch information
1 parent
d385402
commit 5bbe468
Showing
2 changed files
with
69 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
package collections | ||
|
||
import ( | ||
"encoding/json" | ||
"fmt" | ||
|
||
"cosmossdk.io/collections/codec" | ||
) | ||
|
||
func NewJSONValueCodec[T any]() codec.ValueCodec[T] { | ||
return jsonValue[T]{ | ||
typeName: fmt.Sprintf("%T", new(T)), | ||
} | ||
} | ||
|
||
type jsonValue[T any] struct { | ||
typeName string | ||
} | ||
|
||
// Decode implements codec.ValueCodec. | ||
func (jsonValue[T]) Decode(b []byte) (T, error) { | ||
var t T | ||
if err := json.Unmarshal(b, &t); err != nil { | ||
return t, err | ||
} | ||
|
||
return t, nil | ||
} | ||
|
||
// DecodeJSON implements codec.ValueCodec. | ||
func (jsonValue[T]) DecodeJSON(b []byte) (T, error) { | ||
var t T | ||
if err := json.Unmarshal(b, &t); err != nil { | ||
return t, err | ||
} | ||
|
||
return t, nil | ||
} | ||
|
||
// Encode implements codec.ValueCodec. | ||
func (jsonValue[T]) Encode(value T) ([]byte, error) { | ||
return json.Marshal(value) | ||
} | ||
|
||
// EncodeJSON implements codec.ValueCodec. | ||
func (jsonValue[T]) EncodeJSON(value T) ([]byte, error) { | ||
return json.Marshal(value) | ||
} | ||
|
||
// Stringify implements codec.ValueCodec. | ||
func (jsonValue[T]) Stringify(value T) string { | ||
return fmt.Sprintf("%v", value) | ||
} | ||
|
||
// ValueType implements codec.ValueCodec. | ||
func (jv jsonValue[T]) ValueType() string { | ||
return fmt.Sprintf("json(%s)", jv.typeName) | ||
} |