summaryrefslogtreecommitdiff
path: root/encode.go
diff options
context:
space:
mode:
Diffstat (limited to 'encode.go')
-rw-r--r--encode.go30
1 files changed, 27 insertions, 3 deletions
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)