fix: use PutVarint instead of AppendVarint

This commit is contained in:
Jason Song 2022-11-26 22:41:03 +08:00
parent ef4b3673dd
commit ae018b6b48
No known key found for this signature in database
GPG Key ID: 8402EEEE4511A8B5
2 changed files with 42 additions and 7 deletions

View File

@ -204,7 +204,7 @@ func (task *Task) GenerateToken() error {
type LogIndexes []int64
func (i *LogIndexes) FromDB(b []byte) error {
func (indexes *LogIndexes) FromDB(b []byte) error {
reader := bytes.NewReader(b)
for {
v, err := binary.ReadVarint(reader)
@ -214,16 +214,17 @@ func (i *LogIndexes) FromDB(b []byte) error {
}
return fmt.Errorf("binary ReadVarint: %w", err)
}
*i = append(*i, v)
*indexes = append(*indexes, v)
}
}
func (i *LogIndexes) ToDB() ([]byte, error) {
var buf []byte
for _, v := range *i {
buf = binary.AppendVarint(buf, v)
func (indexes *LogIndexes) ToDB() ([]byte, error) {
buf, i := make([]byte, binary.MaxVarintLen64*len(*indexes)), 0
for _, v := range *indexes {
n := binary.PutVarint(buf[i:], v)
i += n
}
return buf, nil
return buf[:i], nil
}
func GetTaskByID(ctx context.Context, id int64) (*Task, error) {

34
models/bots/task_test.go Normal file
View File

@ -0,0 +1,34 @@
// Copyright 2022 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package bots
import (
"math"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestLogIndexes_ToDB(t *testing.T) {
tests := []struct {
indexes LogIndexes
}{
{
indexes: []int64{1, 2, 0, -1, -2, math.MaxInt64, math.MinInt64},
},
}
for _, tt := range tests {
t.Run("", func(t *testing.T) {
got, err := tt.indexes.ToDB()
require.NoError(t, err)
indexes := LogIndexes{}
require.NoError(t, indexes.FromDB(got))
assert.Equal(t, tt.indexes, indexes)
})
}
}