ohler55 / ojg

Optimized JSON for Go
MIT License
857 stars 49 forks source link

Unintentional / Undocumented reuse of buffer? #90

Closed Bios-Marcel closed 2 years ago

Bios-Marcel commented 2 years ago

Look at the following. The results are clearly wrong. I am not sure if this is intended behaviour, but if so, it isn't documented.

package main

import (
    "fmt"

    "github.com/ohler55/ojg/oj"
)

func main() {
    type a struct {
        A string `json:"a"`
    }

    type b struct {
        B string `json:"b"`
    }

    aBytes, _ := oj.Marshal(a{
        A: "a",
    })
    bBytes, _ := oj.Marshal(b{
        B: "b",
    })

    fmt.Println(string(bBytes))
    fmt.Println(string(aBytes))

    //Output:
    //{"b":"b"}
    //{"b":"b"}
}
ohler55 commented 2 years ago

It is wrong, I agree. The buffer is reused but for Marshal it should make a copy before returning. The Writer.MustJSON suffers the same although I might take a different approach with that one and add an optional argument to either copy or not since in many case reuse of the buffer is not an issue. It certainly is with your use case.

I'll get the fix in tonight.

ohler55 commented 2 years ago

Fixed and released as v1.14.3.

ohler55 commented 2 years ago

Thanks for letting me know.

Bios-Marcel commented 2 years ago

I'll just close this. I'll trust that you've fixed this ^^

I just evaluated the library for a new project, meaning I won't test it again for now.

ohler55 commented 2 years ago

Thanks. I did create a unit test for it and verified it failed before the fix and not after.