From ffee5c8516f3f55f82ed5bb8f0a4f340d485fa92 Mon Sep 17 00:00:00 2001 From: Luke Shumaker Date: Wed, 25 Jan 2023 21:05:17 -0700 Subject: Write documentation --- reencode.go | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) (limited to 'reencode.go') diff --git a/reencode.go b/reencode.go index 34c3851..b20a503 100644 --- a/reencode.go +++ b/reencode.go @@ -20,10 +20,21 @@ type speculation struct { indentBuf bytes.Buffer } +// A ReEncoder takes a stream of JSON elements (by way of implementing +// io.Writer and WriteRune), and re-encodes the JSON, writing it to +// the .Out member. +// +// This is useful for prettifying, minifying, sanitizing, and/or +// validating JSON. +// // The memory use of a ReEncoder is O( (CompactIfUnder+1)^2 + depth). type ReEncoder struct { + // The output stream to write the re-encoded JSON to. Out io.Writer + // A JSON document is specified to be a single JSON element; + // but it is often desirable to handle streams of multiple + // JSON elements. AllowMultipleValues bool // Whether to minify the JSON. @@ -88,6 +99,14 @@ type ReEncoder struct { // public API ////////////////////////////////////////////////////////////////// +// Write implements io.Writer; it does what you'd expect, mostly. +// +// Rather than returning the number of bytes written to the output +// stream, it returns the nubmer of bytes from p that it successfully +// handled. This distinction is because *ReEncoder transforms the +// data written to it, and the number of bytes written may be wildly +// different than the number of bytes handled; and that would break +// virtually all users of io.Writer. func (enc *ReEncoder) Write(p []byte) (int, error) { if len(p) == 0 { return 0, nil @@ -113,7 +132,7 @@ func (enc *ReEncoder) Write(p []byte) (int, error) { return len(p), nil } -// Close does what you'd expect, mostly. +// Close implements io.Closer; it does what you'd expect, mostly. // // The *ReEncoder may continue to be written to with new JSON values // if enc.AllowMultipleValues is set. @@ -144,6 +163,15 @@ func (enc *ReEncoder) Close() error { return nil } +// WriteRune write a single Unicode code point, returning the number +// of bytes written to the output stream and any error. +// +// Even when there is no error, the number of bytes written may be +// zero (for example, when the rune is whitespace and the ReEncoder is +// minifying the JSON), or it may be substantially longer than one +// code point's worth (for example, when `\uXXXX` escaping a character +// in a string, or when outputing extra whitespace when the ReEncoder +// is prettifying the JSON). func (enc *ReEncoder) WriteRune(c rune) (n int, err error) { if enc.err != nil { return 0, enc.err -- cgit v1.2.3-54-g00ecf