Skip to content

Commit

Permalink
Merge pull request #85 from whyrusleeping/feat/optimize-write-string
Browse files Browse the repository at this point in the history
optimize anything using WriteString
  • Loading branch information
whyrusleeping authored Aug 18, 2023
2 parents daab9ec + bd09f20 commit f91ae53
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 68 deletions.
6 changes: 3 additions & 3 deletions gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ func emitCborMarshalStringField(w io.Writer, f Field) error {
}
{{ MajorType "cw" "cbg.MajTextString" (print "len(*" .Name ")") }}
if _, err := io.WriteString(w, string(*{{ .Name }})); err != nil {
if _, err := cw.WriteString(string(*{{ .Name }})); err != nil {
return err
}
}
Expand All @@ -324,7 +324,7 @@ func emitCborMarshalStringField(w io.Writer, f Field) error {
if f.Const != nil {
return doTemplate(w, f, `
{{ MajorType "cw" "cbg.MajTextString" (print "len(\"" (Deref .Const) "\")") }}
if _, err := io.WriteString(w, string("{{ .Const }}")); err != nil {
if _, err := cw.WriteString(string("{{ .Const }}")); err != nil {
return err
}
`)
Expand All @@ -337,7 +337,7 @@ func emitCborMarshalStringField(w io.Writer, f Field) error {
}
{{ MajorType "cw" "cbg.MajTextString" (print "len(" .Name ")") }}
if _, err := io.WriteString(w, string({{ .Name }})); err != nil {
if _, err := cw.WriteString(string({{ .Name }})); err != nil {
return err
}
`)
Expand Down
24 changes: 21 additions & 3 deletions io.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,34 @@ var (
type CborWriter struct {
w io.Writer
hbuf []byte

sw io.StringWriter
}

func NewCborWriter(w io.Writer) *CborWriter {
if w, ok := w.(*CborWriter); ok {
return w
}
return &CborWriter{

cw := &CborWriter{
w: w,
hbuf: make([]byte, maxHeaderSize),
}

if sw, ok := w.(io.StringWriter); ok {
cw.sw = sw
}

return cw
}

func (cw *CborWriter) SetWriter(w io.Writer) {
cw.w = w
if sw, ok := w.(io.StringWriter); ok {
cw.sw = sw
} else {
cw.sw = nil
}
}

func (cw *CborWriter) Write(p []byte) (n int, err error) {
Expand All @@ -78,8 +96,8 @@ func (cw *CborWriter) CborWriteHeader(t byte, l uint64) error {
}

func (cw *CborWriter) WriteString(s string) (int, error) {
if sw, ok := cw.w.(io.StringWriter); ok {
return sw.WriteString(s)
if cw.sw != nil {
return cw.sw.WriteString(s)
}
return cw.w.Write([]byte(s))
}
10 changes: 5 additions & 5 deletions testing/cbor_gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit f91ae53

Please sign in to comment.