From ffee5c8516f3f55f82ed5bb8f0a4f340d485fa92 Mon Sep 17 00:00:00 2001 From: Luke Shumaker Date: Wed, 25 Jan 2023 21:05:17 -0700 Subject: Write documentation --- encode.go | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) (limited to 'encode.go') diff --git a/encode.go b/encode.go index 6963e3c..d31f36e 100644 --- a/encode.go +++ b/encode.go @@ -21,6 +21,12 @@ import ( "unsafe" ) +// Encodable is the interface implemented by types that can encode +// themselves to JSON. Encodable is a low-memory-overhead replacement +// for the json.Marshaler interface. +// +// The io.Writer passed to EncodeJSON returns an error if invalid JSON +// is written to it. type Encodable interface { EncodeJSON(w io.Writer) error } @@ -41,6 +47,15 @@ func encodeWriteString(w io.Writer, str string) { } } +// An Encoder encodes and writes values to a stream of JSON elements. +// +// Encoder is analogous to, and has a similar API to the standar +// library's encoding/json.Encoder. Differences are that rather than +// having .SetEscapeHTML and .SetIndent methods, the io.Writer passed +// to it may be a *ReEncoder that has these settings (and more). If +// something more similar to a json.Encoder is desired, +// lowmemjson/compat/json.Encoder offers those .SetEscapeHTML and +// .SetIndent methods. type Encoder struct { w *ReEncoder closeAfterEncode bool @@ -65,6 +80,15 @@ func NewEncoder(w io.Writer) *Encoder { } } +// Encode encodes obj to JSON and writes that JSON to the Encoder's +// output stream. +// +// See the [documentation for encoding/json.Marshal] for details about +// the conversion Go values to JSON; Encode behaves identically to +// that, with the exception that in addition to the json.Marshaler +// interface it also checks for the Encodable interface. +// +// [documentation for encoding/json.Marshal]: https://pkg.go.dev/encoding/json@go1.18#Marshal func (enc *Encoder) Encode(obj any) (err error) { defer func() { if r := recover(); r != nil { @@ -115,8 +139,8 @@ func encode(w io.Writer, val reflect.Value, escaper BackslashEscaper, quote bool if err := obj.EncodeJSON(validator); err != nil { panic(encodeError{&EncodeMethodError{ Type: val.Type(), - Err: err, SourceFunc: "EncodeJSON", + Err: err, }}) } if err := validator.Close(); err != nil && !errors.Is(err, iofs.ErrClosed) { @@ -140,8 +164,8 @@ func encode(w io.Writer, val reflect.Value, escaper BackslashEscaper, quote bool if err != nil { panic(encodeError{&EncodeMethodError{ Type: val.Type(), - Err: err, SourceFunc: "MarshalJSON", + Err: err, }}) } // Use a sub-ReEncoder to check that it's a full element. @@ -170,8 +194,8 @@ func encode(w io.Writer, val reflect.Value, escaper BackslashEscaper, quote bool if err != nil { panic(encodeError{&EncodeMethodError{ Type: val.Type(), - Err: err, SourceFunc: "MarshalText", + Err: err, }}) } encodeStringFromBytes(w, escaper, text) -- cgit v1.2.3