fastjson

package module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2024 License: Apache-2.0, MIT Imports: 5 Imported by: 24

README

Build Status

fastjson: fast JSON encoder for Go

Package fastjson provides a library and code generator for fast JSON encoding.

The supplied code generator (cmd/generate-fastjson) generates JSON marshalling methods for all exported types within a specified package.

Requirements

Go 1.19+

License

Apache 2.0.

Installation

go get -u go.elastic.co/fastjson/...

Code generation

Package fastjson is intended to be used with the accompanying code generator, cmd/generate-fastjson. This code generator will parse the Go code of a specified package, and write out fastjson marshalling method (MarshalFastJSON) definitions for the exported types in the package.

You can provide your own custom marshalling logic for a type by defining a MarshalFastJSON method for it. The generator will not generate methods for those types with existing marshalling methods.

Usage
generate-fastjson <package>
  -f    remove the output file if it exists
  -o string
        file to which output will be written (default "-")
Custom omitempty extension

The standard json struct tags defined by encoding/json are honoured, enabling you to generate fastjson-marshalling code for your existing code.

We extend the omitempty option by enabling you to define an unexported method on your type T, func (T) isZero() bool, which will be called to determine whether or not the value is considered empty. This enables omitempty on non-pointer struct types.

Example

Given the following package:

package example

type Foo struct {
	Bar Bar `json:",omitempty"`
}

type Bar struct {
	Baz Baz
	Qux *Qux `json:"quux,omitempty"`
}

func (b Bar) isZero() bool {
	return b == (Bar{})
}

type Baz struct {
}

func (Baz) MarshalFastJSON(w *fastjson.Writer) error {
}

type Qux struct{}

Assuming we're in the package directory, we would generate the methods like so, which will write a Go file to stdout:

generate-fastjson .

Output:

// Code generated by "generate-fastjson". DO NOT EDIT.

package example

import (
	"go.elastic.co/fastjson"
)

func (v *Foo) MarshalFastJSON(w *fastjson.Writer) error {
	w.RawByte('{')
	if !v.Bar.isZero() {
		w.RawString("\"Bar\":")
		if err := v.Bar.MarshalFastJSON(w); err != nil && firstErr == nil {
			firstErr == err
		}
	}
	w.RawByte('}')
	return nil
}

func (v *Bar) MarshalFastJSON(w *fastjson.Writer) error {
	var firstErr error
	w.RawByte('{')
	w.RawString("\"Baz\":")
	if err := v.Baz.MarshalFastJSON(w); err != nil && firstErr == nil {
		firstErr = err
	}
	if v.Qux != nil {
		w.RawString(",\"quux\":")
		if err := v.Qux.MarshalFastJSON(w); err != nil && firstErr == nil {
			firstErr == err
		}
	}
	w.RawByte('}')
	return firstErr
}

func (v *Qux) MarshalFastJSON(w *fastjson.Writer) error {
	w.RawByte('{')
	w.RawByte('}')
	return nil
}

Documentation

Overview

Package fastjson provides a library for fast JSON encoding, optimised for static code generation.

Fastjson functions and interfaces are structured such that all encoding appends to a buffer, enabling buffer reuse without forcing specific mechanisms such as sync.Pool. This enables zero-allocation encoding without incurring any concurrency overhead in certain applications.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Marshal

func Marshal(w *Writer, v interface{}) error

Marshal marshals v as JSON to w.

For all basic types, Marshal uses w's methods to marshal the values directly. If v implements Marshaler, its MarshalFastJSON method will be used; if v implements Appender, its AppendJSON method will be used, and it is assumed to append valid JSON. As a final resort, we use json.Marshal.

Where json.Marshal is used internally (see above), errors or panics produced by json.Marshal will be encoded as JSON objects, with special keys "__ERROR__" for errors, and "__PANIC__" for panics. e.g. if json.Marshal panics due to a broken json.Marshaler implementation or assumption, then Marshal will encode the panic as

{"__PANIC__": "panic calling MarshalJSON for type Foo: reason"}

Marshal returns the first error encountered.

Types

type Appender

type Appender interface {
	// AppendJSON appends the JSON representation of the value to the
	// buffer, and returns the extended buffer.
	//
	// AppendJSON is required not to panic or fail.
	AppendJSON([]byte) []byte
}

Appender defines an interface that types can implement to append their JSON representation to a buffer.

type Marshaler

type Marshaler interface {
	// MarshalFastJSON writes a JSON representation of the type to w.
	//
	// MarshalFastJSON is expected to suppress any panics. Depending
	// on the application, it may be expected that MarshalFastJSON
	// writes valid JSON to w, even in error cases.
	//
	// The returned error will be propagated up through to callers of
	// fastjson.Marshal.
	MarshalFastJSON(w *Writer) error
}

Marshaler defines an interface that types can implement to provide fast JSON marshaling.

type Writer

type Writer struct {
	// contains filtered or unexported fields
}

Writer is a JSON writer, appending to an internal buffer.

Writer is not safe for concurrent use. A Writer can be reset and reused, which will reuse the underlying buffer.

func (*Writer) Bool

func (w *Writer) Bool(v bool)

Bool appends v to the buffer.

func (*Writer) Bytes

func (w *Writer) Bytes() []byte

Bytes returns the internal buffer. The result is invalidated when Reset is called.

func (*Writer) Float32

func (w *Writer) Float32(n float32)

Float32 appends n to the buffer.

func (*Writer) Float64

func (w *Writer) Float64(n float64)

Float64 appends n to the buffer.

func (*Writer) Int64

func (w *Writer) Int64(n int64)

Int64 appends n to the buffer.

func (*Writer) RawByte

func (w *Writer) RawByte(c byte)

RawByte appends c to the buffer.

func (*Writer) RawBytes

func (w *Writer) RawBytes(data []byte)

RawBytes appends data, unmodified, to the buffer.

func (*Writer) RawString

func (w *Writer) RawString(s string)

RawString appends s to the buffer.

func (*Writer) Reset

func (w *Writer) Reset()

Reset resets the internal []byte buffer to empty.

func (*Writer) Rewind

func (w *Writer) Rewind(size int)

Rewind rewinds the buffer such that it has size bytes, dropping everything proceeding.

func (*Writer) Size

func (w *Writer) Size() int

Size returns the current size of the buffer. Size is typically used in conjunction with Rewind, to mark a position to which the writer may later be rewound.

func (*Writer) String

func (w *Writer) String(s string)

String appends s, quoted and escaped, to the buffer.

func (*Writer) StringContents

func (w *Writer) StringContents(s string)

StringContents is the same as String, but without the surrounding quotes.

func (*Writer) Time

func (w *Writer) Time(t time.Time, layout string)

Time appends t to the buffer, formatted according to layout.

The encoded time is not surrounded by quotes; it is the responsibility of the caller to ensure the formatted time is quoted as necessary.

func (*Writer) Uint64

func (w *Writer) Uint64(n uint64)

Uint64 appends n to the buffer.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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