优化代码

This commit is contained in:
GoEdgeLab
2024-03-28 17:18:00 +08:00
parent 04bff814d9
commit 7a12a78359
3 changed files with 70 additions and 18 deletions

View File

@@ -75,7 +75,22 @@ func (this *Table[T]) Set(key string, value T) error {
}
return this.WriteTx(func(tx *Tx[T]) error {
return this.set(tx, key, valueBytes, value)
return this.set(tx, key, valueBytes, value, false)
})
}
func (this *Table[T]) Insert(key string, value T) error {
if len(key) > KeyMaxLength {
return ErrKeyTooLong
}
valueBytes, err := this.encoder.Encode(value)
if err != nil {
return err
}
return this.WriteTx(func(tx *Tx[T]) error {
return this.set(tx, key, valueBytes, value, true)
})
}
@@ -283,7 +298,7 @@ func (this *Table[T]) deleteKeys(tx *Tx[T], key ...string) error {
return nil
}
func (this *Table[T]) set(tx *Tx[T], key string, valueBytes []byte, value T) error {
func (this *Table[T]) set(tx *Tx[T], key string, valueBytes []byte, value T, insertOnly bool) error {
var keyBytes = this.FullKey(key)
var batch = tx.batch
@@ -292,23 +307,26 @@ func (this *Table[T]) set(tx *Tx[T], key string, valueBytes []byte, value T) err
var oldValue T
var oldFound bool
var countFields = len(this.fieldNames)
if countFields > 0 {
oldValueBytes, closer, getErr := batch.Get(keyBytes)
if getErr != nil {
if !IsKeyNotFound(getErr) {
return getErr
}
} else {
defer func() {
_ = closer.Close()
}()
var decodeErr error
oldValue, decodeErr = this.encoder.Decode(oldValueBytes)
if decodeErr != nil {
return decodeErr
if !insertOnly {
if countFields > 0 {
oldValueBytes, closer, getErr := batch.Get(keyBytes)
if getErr != nil {
if !IsKeyNotFound(getErr) {
return getErr
}
} else {
defer func() {
_ = closer.Close()
}()
var decodeErr error
oldValue, decodeErr = this.encoder.Decode(oldValueBytes)
if decodeErr != nil {
return decodeErr
}
oldFound = true
}
oldFound = true
}
}

View File

@@ -37,7 +37,24 @@ func (this *Tx[T]) Set(key string, value T) error {
return err
}
return this.table.set(this, key, valueBytes, value)
return this.table.set(this, key, valueBytes, value, false)
}
func (this *Tx[T]) Insert(key string, value T) error {
if this.readOnly {
return errors.New("can not set value in readonly transaction")
}
if len(key) > KeyMaxLength {
return ErrKeyTooLong
}
valueBytes, err := this.table.encoder.Encode(value)
if err != nil {
return err
}
return this.table.set(this, key, valueBytes, value, true)
}
func (this *Tx[T]) Get(key string) (value T, err error) {

View File

@@ -0,0 +1,17 @@
// Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
package memutils_test
import (
"github.com/TeaOSLab/EdgeNode/internal/utils/mem"
"testing"
)
func TestSystemMemoryGB(t *testing.T) {
t.Log(memutils.SystemMemoryGB())
t.Log(memutils.SystemMemoryGB())
t.Log(memutils.SystemMemoryGB())
t.Log(memutils.SystemMemoryBytes())
t.Log(memutils.SystemMemoryBytes())
t.Log(memutils.SystemMemoryBytes()>>30, "GB")
}