You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ntool-biz/ngochess/katago/serializer.go

52 lines
841 B
Go

11 months ago
package katago
import (
"bytes"
"encoding/json"
"git.noahlan.cn/noahlan/ntool/njson"
)
type Serializer struct {
contentBuf *bytes.Buffer
lastJson string
}
func NewSerializer() *Serializer {
ret := &Serializer{
contentBuf: bytes.NewBuffer([]byte{}),
}
return ret
}
func (s *Serializer) reset() {
s.contentBuf.Reset()
}
func (s *Serializer) LastJson() string {
return s.lastJson
}
func (s *Serializer) Marshal(v any) ([]byte, error) {
return njson.Marshal(v)
}
func (s *Serializer) Unmarshal(line string, v any) (bool, error) {
s.contentBuf.WriteString(line)
if json.Valid(s.contentBuf.Bytes()) {
defer func() {
s.lastJson = s.contentBuf.String()
s.reset()
}()
err := njson.Unmarshal(s.contentBuf.Bytes(), v)
if err != nil {
return false, err
}
return true, nil
} else {
return false, nil
}
}