codec

package
v0.0.0-...-70b8d44 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 21, 2026 License: Apache-2.0 Imports: 4 Imported by: 0

Documentation

Overview

Package codec provides composable JSON codecs over encoding/json/jsontext

Index

Constants

This section is empty.

Variables

View Source
var (
	String  = Text[string]()
	Bool    = Boolean[bool]()
	Int     = Number[int]()
	Int64   = Number[int64]()
	Float64 = Number[float64]()

	ErrUnexpectedToken = errors.New("unexpected JSON token")
	ErrUnexpectedEnd   = errors.New("unexpected end of JSON input")
)

Functions

func DecodeFrom

func DecodeFrom[T any](c Codec[T], r io.Reader) (T, error)

DecodeFrom reads a single JSON value from r using the given codec

func EncodeTo

func EncodeTo[T any](c Codec[T], w io.Writer, v T) error

EncodeTo writes v to w as a single JSON value using the given codec

Types

type Codec

type Codec[T any] interface {
	Decode(*jsontext.Decoder) (T, error)
	Encode(*jsontext.Encoder, T) error
}

Codec reads and writes a single Go value as a JSON value

func Boolean

func Boolean[T ~bool]() Codec[T]

Boolean returns a codec for any bool-like type

func Map

func Map[T any](elem Codec[T]) Codec[map[string]T]

Map returns a codec for a JSON object with uniformly typed members

func Number

func Number[T Numeric]() Codec[T]

Number returns a codec for any numeric type

func Optional

func Optional[T any](elem Codec[T]) Codec[*T]

Optional returns a codec mapping JSON null to a nil pointer

func Slice

func Slice[T any](elem Codec[T]) Codec[[]T]

Slice returns a codec for a JSON array of the element codec's type

func Struct

func Struct[S any](fields ...StructField[S]) Codec[S]

Struct returns a codec for a JSON object with statically known members

func Text

func Text[T ~string]() Codec[T]

Text returns a codec for any string-like type

type Numeric

type Numeric interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 |
		~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
		~float32 | ~float64
}

Numeric is any Go type whose JSON representation is a number

type StructField

type StructField[S any] interface {
	Name() string
	// contains filtered or unexported methods
}

StructField binds one JSON object member to a field of struct S

func Field

func Field[S, T any](
	name string, c Codec[T], ptr func(*S) *T,
) StructField[S]

Field binds a named JSON object member to a field of struct S. The ptr function returns the address of that field in a given struct value

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL