新增压缩功能-LZS算法

This commit is contained in:
lanrenwo
2023-01-17 12:09:04 +08:00
parent 70c82b8baa
commit 768e137ff9
12 changed files with 212 additions and 23 deletions

View File

@@ -0,0 +1,35 @@
package sessdata
import (
"github.com/lanrenwo/lzsgo"
)
type CmpEncoding interface {
Compress(src []byte, dst []byte) (int, error)
Uncompress(src []byte, dst []byte) (int, error)
}
type LzsgoCmp struct {
}
func (l LzsgoCmp) Compress(src []byte, dst []byte) (int, error) {
n, err := lzsgo.Compress(src, dst)
return n, err
}
func (l LzsgoCmp) Uncompress(src []byte, dst []byte) (int, error) {
n, err := lzsgo.Uncompress(src, dst)
return n, err
}
// type Lz4Cmp struct {
// c lz4.Compressor
// }
// func (l Lz4Cmp) Compress(src []byte, dst []byte) (int, error) {
// return l.c.CompressBlock(src, dst)
// }
// func (l Lz4Cmp) Uncompress(src []byte, dst []byte) (int, error) {
// return lz4.UncompressBlock(src, dst)
// }

View File

@@ -0,0 +1,28 @@
package sessdata
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestLzsCompress(t *testing.T) {
var (
n int
err error
)
assert := assert.New(t)
c := LzsgoCmp{}
s := "hello anylink, you are best!"
src := []byte(strings.Repeat(s, 50))
comprBuf := make([]byte, 2048)
n, err = c.Compress(src, comprBuf)
assert.Nil(err)
unprBuf := make([]byte, 2048)
n, err = c.Uncompress(comprBuf[:n], unprBuf)
assert.Nil(err)
assert.Equal(src, unprBuf[:n])
}

View File

@@ -54,6 +54,9 @@ type ConnSession struct {
PayloadOutDtls chan *Payload // Dtls的数据
// dSess *DtlsSession
dSess *atomic.Value
// compress
CstpPickCmp CmpEncoding
DtlsPickCmp CmpEncoding
}
type DtlsSession struct {
@@ -359,6 +362,30 @@ func (cs *ConnSession) RateLimit(byt int, isUp bool) error {
return cs.Limit.Wait(byt)
}
func (cs *ConnSession) SetPickCmp(cate, encoding string) (string, bool) {
var cmpName string
if !base.Cfg.Compression {
return cmpName, false
}
var cmp CmpEncoding
switch {
// case strings.Contains(encoding, "oc-lz4"):
// cmpName = "oc-lz4"
// cmp = Lz4Cmp{}
case strings.Contains(encoding, "lzs"):
cmpName = "lzs"
cmp = LzsgoCmp{}
default:
return cmpName, false
}
if cate == "cstp" {
cs.CstpPickCmp = cmp
} else {
cs.DtlsPickCmp = cmp
}
return cmpName, true
}
func SToken2Sess(stoken string) *Session {
stoken = strings.TrimSpace(stoken)
sarr := strings.Split(stoken, "@")

View File

@@ -1,8 +1,10 @@
package sessdata
import (
"fmt"
"testing"
"github.com/bjdgyc/anylink/base"
"github.com/stretchr/testify/assert"
)
@@ -34,5 +36,23 @@ func TestConnSession(t *testing.T) {
err = cSess.RateLimit(200, false)
ast.Nil(err)
ast.Equal(cSess.BandwidthDown.Load(), uint32(200))
var (
cmpName string
ok bool
)
base.Cfg.Compression = true
cmpName, ok = cSess.SetPickCmp("cstp", "oc-lz4,lzs")
fmt.Println(cmpName, ok)
ast.True(ok)
ast.Equal(cmpName, "lzs")
cmpName, ok = cSess.SetPickCmp("dtls", "lzs")
ast.True(ok)
ast.Equal(cmpName, "lzs")
cmpName, ok = cSess.SetPickCmp("dtls", "test")
ast.False(ok)
ast.Equal(cmpName, "")
cSess.Close()
}