Skip to content

Commit

Permalink
refactor: clone bytes (#640)
Browse files Browse the repository at this point in the history
Signed-off-by: James Yean <[email protected]>
  • Loading branch information
ifplusor authored Oct 18, 2023
1 parent a3dd7d0 commit 5712f51
Show file tree
Hide file tree
Showing 5 changed files with 39 additions and 5 deletions.
17 changes: 17 additions & 0 deletions lib/bytes/clone_go119.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// SPDX-FileCopyrightText: 2023 Linkall Inc.
//
// SPDX-License-Identifier: Apache-2.0

//go:build !go1.20

package bytes

// Clone returns a copy of b[:len(b)].
// The result may have additional unused capacity.
// Clone(nil) returns nil.
func Clone(b []byte) []byte {
if b == nil {
return nil
}
return append([]byte{}, b...)
}
11 changes: 11 additions & 0 deletions lib/bytes/clone_go120.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// SPDX-FileCopyrightText: 2023 Linkall Inc.
//
// SPDX-License-Identifier: Apache-2.0

//go:build go1.20

package bytes

import "bytes"

var Clone = bytes.Clone
9 changes: 6 additions & 3 deletions pkg/template/json/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,18 @@ package json

import (
// standard libraries.
"bytes"
stdbytes "bytes"

// third-party libraries.
"github.com/ohler55/ojg/jp"

// first-party libraries.
"github.com/vanus-labs/vanus/lib/bytes"
)

type templateGenerator struct {
stack generatorStack
buf bytes.Buffer
buf stdbytes.Buffer
segments []templateSegment
}

Expand Down Expand Up @@ -164,7 +167,7 @@ func (g *templateGenerator) packLiteral() {
bs := g.buf.Bytes()
if len(bs) != 0 {
g.segments = append(g.segments, &literalSegment{
val: append([]byte{}, bs...),
val: bytes.Clone(bs),
})
g.buf.Reset()
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/template/text/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ func parse(text string) ([]templateSegment, error) {
return
}
segments = append(segments, &textSegment{
text: append([]byte{}, buf.Bytes()...),
text: bytes.Clone(buf.Bytes()),
})
buf.Reset()
}
Expand Down
5 changes: 4 additions & 1 deletion server/store/meta/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ package meta
import (
// third-party libraries.
"github.com/huandu/skiplist"

// first-party libraries.
"github.com/vanus-labs/vanus/lib/bytes"
)

func update(m *skiplist.SkipList, key []byte, value interface{}) {
Expand All @@ -32,7 +35,7 @@ func set(m *skiplist.SkipList, key []byte, value interface{}) {
switch val := value.(type) {
case []byte:
// Make a copy to avoid modifying value outside.
bs := append([]byte{}, val...)
bs := bytes.Clone(val)
m.Set(key, bs)
default:
m.Set(key, value)
Expand Down

0 comments on commit 5712f51

Please sign in to comment.