diff options
author | Luke Shumaker <lukeshu@lukeshu.com> | 2023-01-25 21:05:17 -0700 |
---|---|---|
committer | Luke Shumaker <lukeshu@lukeshu.com> | 2023-01-26 00:45:27 -0700 |
commit | ffee5c8516f3f55f82ed5bb8f0a4f340d485fa92 (patch) | |
tree | 0c10526b1ea57b043230402e9378b341c6966965 /reencode.go | |
parent | 4148776399cb7ea5e10c74dc465e4e1e682cb399 (diff) |
Write documentationv0.2.0
Diffstat (limited to 'reencode.go')
-rw-r--r-- | reencode.go | 30 |
1 files changed, 29 insertions, 1 deletions
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 |