segmentio/encoding

Proposal: add an option to prevent encoder from adding a newline on Encode

Jerska opened this issue · 3 comments

Hi there!

Thanks for this amazing lib that allowed me to get close to 10x perf improvements on a project for both Marshaling & Unmarshaling use-cases.

A small suggestion I'd have following my usage of library would be to add an option to prevent adding a newline at the end of Encode.
For manual crafting of a JSON without newlines, this behavior requires to add a Truncate call on the byte buffer that is both easy to forget & confusing for readers.

val := "foo"

var buf bytes.Buffer
buf.WriteByte('[')
encoder := json.NewEncoder(&buf)
encoder.Encode(val)
buf.Truncate(buf.Len() - 1) // Remove useless newline
buf.WriteByte(']')

// Outputs:
// ["foo"]

// Without the trucate, outputs:
// ["foo"
// ]

https://go.dev/play/p/4Jkoe_A6sk0

Your version of Encoder already has a few non-standard options (e.g. SetTrustRawMessage), so I believe this could be another one, e.g. SetNoExtraNewline.
Is this an addition you'd be open to? I'd be happy to open a PR.

Hello @Jerska, thanks for reaching out!

The suggestion you make sound fine to add, we add the newline to be compatible with the behavior of encoding/json, but I can imagine it could be useful to disable in some cases.

Would you have the time to submit a pull request to make the change?

Thank you for the answer. I'll open a PR today. :)

I've just opened #119 . :)