Compare commits
No commits in common. "master" and "v0.0.2" have entirely different histories.
82
circle.go
82
circle.go
@ -4,10 +4,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"os"
|
|
||||||
"runtime"
|
|
||||||
"sync"
|
"sync"
|
||||||
"sync/atomic"
|
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -16,90 +13,79 @@ type StarBuffer struct {
|
|||||||
io.Writer
|
io.Writer
|
||||||
io.Closer
|
io.Closer
|
||||||
datas []byte
|
datas []byte
|
||||||
pStart uint64
|
pStart int
|
||||||
pEnd uint64
|
pEnd int
|
||||||
cap uint64
|
cap int
|
||||||
isClose atomic.Value
|
isClose bool
|
||||||
isEnd atomic.Value
|
isEnd bool
|
||||||
rmu sync.Mutex
|
rmu sync.Mutex
|
||||||
wmu sync.Mutex
|
wmu sync.Mutex
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewStarBuffer(cap uint64) *StarBuffer {
|
func NewStarBuffer(cap int) *StarBuffer {
|
||||||
rtnBuffer := new(StarBuffer)
|
rtnBuffer := new(StarBuffer)
|
||||||
rtnBuffer.cap = cap
|
rtnBuffer.cap = cap
|
||||||
rtnBuffer.datas = make([]byte, cap)
|
rtnBuffer.datas = make([]byte, cap)
|
||||||
rtnBuffer.isClose.Store(false)
|
|
||||||
rtnBuffer.isEnd.Store(false)
|
|
||||||
return rtnBuffer
|
return rtnBuffer
|
||||||
}
|
}
|
||||||
|
|
||||||
func (star *StarBuffer) Free() uint64 {
|
func (star *StarBuffer) Free() int {
|
||||||
return star.cap - star.Len()
|
return star.cap - star.Len()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (star *StarBuffer) Cap() uint64 {
|
func (star *StarBuffer) Cap() int {
|
||||||
return star.cap
|
return star.cap
|
||||||
}
|
}
|
||||||
|
|
||||||
func (star *StarBuffer) Len() uint64 {
|
func (star *StarBuffer) Len() int {
|
||||||
if star.pEnd >= star.pStart {
|
length := star.pEnd - star.pStart
|
||||||
return star.pEnd - star.pStart
|
if length < 0 {
|
||||||
|
return star.cap + length - 1
|
||||||
}
|
}
|
||||||
return star.pEnd - star.pStart + star.cap
|
return length
|
||||||
}
|
}
|
||||||
|
|
||||||
func (star *StarBuffer) getByte() (byte, error) {
|
func (star *StarBuffer) getByte() (byte, error) {
|
||||||
if star.isClose.Load().(bool) || (star.Len() == 0 && star.isEnd.Load().(bool)) {
|
if star.isClose || (star.isEnd && star.Len() == 0) {
|
||||||
return 0, io.EOF
|
return 0, io.EOF
|
||||||
}
|
}
|
||||||
if star.Len() == 0 {
|
if star.Len() == 0 {
|
||||||
return 0, os.ErrNotExist
|
return 0, errors.New("no byte available now")
|
||||||
}
|
}
|
||||||
nowPtr := star.pStart
|
data := star.datas[star.pStart]
|
||||||
nextPtr := star.pStart + 1
|
star.pStart++
|
||||||
if nextPtr >= star.cap {
|
if star.pStart == star.cap {
|
||||||
nextPtr = 0
|
star.pStart = 0
|
||||||
}
|
|
||||||
data := star.datas[nowPtr]
|
|
||||||
ok := atomic.CompareAndSwapUint64(&star.pStart, nowPtr, nextPtr)
|
|
||||||
if !ok {
|
|
||||||
return 0, os.ErrInvalid
|
|
||||||
}
|
}
|
||||||
return data, nil
|
return data, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (star *StarBuffer) putByte(data byte) error {
|
func (star *StarBuffer) putByte(data byte) error {
|
||||||
if star.isClose.Load().(bool) {
|
if star.isClose || star.isEnd {
|
||||||
return io.EOF
|
return io.EOF
|
||||||
}
|
}
|
||||||
nowPtr := star.pEnd
|
kariEnd := star.pEnd + 1
|
||||||
kariEnd := nowPtr + 1
|
|
||||||
if kariEnd == star.cap {
|
if kariEnd == star.cap {
|
||||||
kariEnd = 0
|
kariEnd = 0
|
||||||
}
|
}
|
||||||
if kariEnd == atomic.LoadUint64(&star.pStart) {
|
if kariEnd == star.pStart {
|
||||||
for {
|
for {
|
||||||
time.Sleep(time.Microsecond)
|
time.Sleep(time.Microsecond)
|
||||||
runtime.Gosched()
|
if kariEnd != star.pStart {
|
||||||
if kariEnd != atomic.LoadUint64(&star.pStart) {
|
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
star.datas[nowPtr] = data
|
star.datas[star.pEnd] = data
|
||||||
if ok := atomic.CompareAndSwapUint64(&star.pEnd, nowPtr, kariEnd); !ok {
|
star.pEnd = kariEnd
|
||||||
return os.ErrInvalid
|
|
||||||
}
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (star *StarBuffer) Close() error {
|
func (star *StarBuffer) Close() error {
|
||||||
star.isClose.Store(true)
|
star.isClose = true
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
func (star *StarBuffer) Read(buf []byte) (int, error) {
|
func (star *StarBuffer) Read(buf []byte) (int, error) {
|
||||||
if star.isClose.Load().(bool) || (star.Len() == 0 && star.isEnd.Load().(bool)) {
|
if star.isClose {
|
||||||
return 0, io.EOF
|
return 0, io.EOF
|
||||||
}
|
}
|
||||||
if buf == nil {
|
if buf == nil {
|
||||||
@ -112,17 +98,10 @@ func (star *StarBuffer) Read(buf []byte) (int, error) {
|
|||||||
data, err := star.getByte()
|
data, err := star.getByte()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err == io.EOF {
|
if err == io.EOF {
|
||||||
if sum == 0 {
|
|
||||||
return sum, err
|
return sum, err
|
||||||
}
|
}
|
||||||
return sum, nil
|
return sum, nil
|
||||||
}
|
}
|
||||||
if err == os.ErrNotExist {
|
|
||||||
i--
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
return sum, nil
|
|
||||||
}
|
|
||||||
buf[i] = data
|
buf[i] = data
|
||||||
sum++
|
sum++
|
||||||
}
|
}
|
||||||
@ -130,11 +109,8 @@ func (star *StarBuffer) Read(buf []byte) (int, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (star *StarBuffer) Write(bts []byte) (int, error) {
|
func (star *StarBuffer) Write(bts []byte) (int, error) {
|
||||||
if bts == nil && !star.isEnd.Load().(bool) {
|
if bts == nil || star.isClose {
|
||||||
star.isEnd.Store(true)
|
star.isEnd = true
|
||||||
return 0, nil
|
|
||||||
}
|
|
||||||
if bts == nil || star.isClose.Load().(bool) {
|
|
||||||
return 0, io.EOF
|
return 0, io.EOF
|
||||||
}
|
}
|
||||||
star.wmu.Lock()
|
star.wmu.Lock()
|
||||||
|
@ -1,86 +0,0 @@
|
|||||||
package stario
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"sync/atomic"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func Test_Circle(t *testing.T) {
|
|
||||||
buf := NewStarBuffer(2048)
|
|
||||||
go func() {
|
|
||||||
for {
|
|
||||||
//fmt.Println("write start")
|
|
||||||
buf.Write([]byte("中华人民共和国\n"))
|
|
||||||
//fmt.Println("write success")
|
|
||||||
time.Sleep(time.Millisecond * 50)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
cpp := ""
|
|
||||||
go func() {
|
|
||||||
time.Sleep(time.Second * 3)
|
|
||||||
for {
|
|
||||||
cache := make([]byte, 64)
|
|
||||||
ints, err := buf.Read(cache)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Println("read error", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if ints != 0 {
|
|
||||||
cpp += string(cache[:ints])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
time.Sleep(time.Second * 13)
|
|
||||||
fmt.Println(cpp)
|
|
||||||
}
|
|
||||||
|
|
||||||
func Test_Circle_Speed(t *testing.T) {
|
|
||||||
buf := NewStarBuffer(1048976)
|
|
||||||
count := uint64(0)
|
|
||||||
for i := 1; i <= 10; i++ {
|
|
||||||
go func() {
|
|
||||||
for {
|
|
||||||
buf.putByte('a')
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
for i := 1; i <= 10; i++ {
|
|
||||||
go func() {
|
|
||||||
for {
|
|
||||||
_, err := buf.getByte()
|
|
||||||
if err == nil {
|
|
||||||
atomic.AddUint64(&count, 1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
time.Sleep(time.Second * 10)
|
|
||||||
fmt.Println(count)
|
|
||||||
}
|
|
||||||
|
|
||||||
func Test_Circle_Speed2(t *testing.T) {
|
|
||||||
buf := NewStarBuffer(8192)
|
|
||||||
count := uint64(0)
|
|
||||||
for i := 1; i <= 10; i++ {
|
|
||||||
go func() {
|
|
||||||
for {
|
|
||||||
buf.Write([]byte("hello world b612 hello world b612 b612 b612 b612 b612 b612"))
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
for i := 1; i <= 10; i++ {
|
|
||||||
go func() {
|
|
||||||
for {
|
|
||||||
mybuf := make([]byte, 1024)
|
|
||||||
j, err := buf.Read(mybuf)
|
|
||||||
if err == nil {
|
|
||||||
atomic.AddUint64(&count, uint64(j))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
time.Sleep(time.Second * 10)
|
|
||||||
fmt.Println(float64(count) / 10 / 1024 / 1024)
|
|
||||||
}
|
|
55
fn.go
55
fn.go
@ -1,55 +0,0 @@
|
|||||||
package stario
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
var ERR_TIMEOUT = errors.New("TIME OUT")
|
|
||||||
|
|
||||||
func WaitUntilTimeout(tm time.Duration, fn func(chan struct{}) error) error {
|
|
||||||
var err error
|
|
||||||
finished := make(chan struct{})
|
|
||||||
imout := make(chan struct{})
|
|
||||||
go func() {
|
|
||||||
err = fn(imout)
|
|
||||||
finished <- struct{}{}
|
|
||||||
}()
|
|
||||||
select {
|
|
||||||
case <-finished:
|
|
||||||
return err
|
|
||||||
case <-time.After(tm):
|
|
||||||
close(imout)
|
|
||||||
return ERR_TIMEOUT
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func WaitUntilFinished(fn func() error) <-chan error {
|
|
||||||
finished := make(chan error)
|
|
||||||
go func() {
|
|
||||||
err := fn()
|
|
||||||
finished <- err
|
|
||||||
}()
|
|
||||||
return finished
|
|
||||||
}
|
|
||||||
|
|
||||||
func WaitUntilTimeoutFinished(tm time.Duration, fn func(chan struct{}) error) <-chan error {
|
|
||||||
var err error
|
|
||||||
finished := make(chan struct{})
|
|
||||||
result := make(chan error)
|
|
||||||
imout := make(chan struct{})
|
|
||||||
go func() {
|
|
||||||
err = fn(imout)
|
|
||||||
finished <- struct{}{}
|
|
||||||
}()
|
|
||||||
go func() {
|
|
||||||
select {
|
|
||||||
case <-finished:
|
|
||||||
result <- err
|
|
||||||
case <-time.After(tm):
|
|
||||||
close(imout)
|
|
||||||
result <- ERR_TIMEOUT
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
return result
|
|
||||||
}
|
|
67
go.sum
67
go.sum
@ -1,67 +0,0 @@
|
|||||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
|
||||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
|
||||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
|
||||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
|
||||||
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
|
|
||||||
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
|
|
||||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
|
||||||
golang.org/x/crypto v0.26.0 h1:RrRspgV4mU+YwB4FYnuBoKsUapNIL5cohGAmSH3azsw=
|
|
||||||
golang.org/x/crypto v0.26.0/go.mod h1:GY7jblb9wI+FOo5y8/S2oY4zWP07AkOJ4+jxCqdqn54=
|
|
||||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
|
||||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
|
||||||
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
|
||||||
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
|
||||||
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
|
||||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
|
||||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
|
||||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
|
||||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
|
||||||
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
|
||||||
golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
|
|
||||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
|
||||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
|
||||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
|
||||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
|
||||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
|
||||||
golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
|
|
||||||
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
|
||||||
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
|
||||||
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
|
||||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
|
||||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
|
||||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
|
||||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
|
||||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
|
||||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
|
||||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
|
||||||
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
|
||||||
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
|
||||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
|
||||||
golang.org/x/sys v0.23.0 h1:YfKFowiIMvtgl1UERQoTPPToxltDeZfbj4H7dVUCwmM=
|
|
||||||
golang.org/x/sys v0.23.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
|
||||||
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
|
|
||||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
|
||||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
|
||||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
|
||||||
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
|
|
||||||
golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
|
|
||||||
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
|
|
||||||
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
|
|
||||||
golang.org/x/term v0.23.0 h1:F6D4vR+EHoL9/sWAWgAR1H2DcHr4PareCbAaCo1RpuU=
|
|
||||||
golang.org/x/term v0.23.0/go.mod h1:DgV24QBUrK6jhZXl+20l6UWznPlwAHm1Q1mGHtydmSk=
|
|
||||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
|
||||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
|
||||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
|
||||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
|
||||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
|
||||||
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
|
||||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
|
||||||
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
|
||||||
golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
|
|
||||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
|
||||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
|
||||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
|
||||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
|
||||||
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
|
|
||||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
|
|
||||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
|
297
io.go
297
io.go
@ -3,152 +3,50 @@ package stario
|
|||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
"fmt"
|
"fmt"
|
||||||
"golang.org/x/crypto/ssh/terminal"
|
|
||||||
"os"
|
"os"
|
||||||
"runtime"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/ssh/terminal"
|
||||||
)
|
)
|
||||||
|
|
||||||
type InputMsg struct {
|
type InputMsg struct {
|
||||||
msg string
|
msg string
|
||||||
err error
|
err error
|
||||||
skipSliceSigErr bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func Passwd(hint string, defaultVal string) InputMsg {
|
func Passwd(hint string, defaultVal string) InputMsg {
|
||||||
return passwd(hint, defaultVal, "", false)
|
return passwd(hint, defaultVal, "")
|
||||||
}
|
}
|
||||||
|
|
||||||
func PasswdWithMask(hint string, defaultVal string, mask string) InputMsg {
|
func PasswdWithMask(hint string, defaultVal string, mask string) InputMsg {
|
||||||
return passwd(hint, defaultVal, mask, false)
|
return passwd(hint, defaultVal, mask)
|
||||||
}
|
}
|
||||||
|
|
||||||
func PasswdResponseSignal(hint string, defaultVal string) InputMsg {
|
func passwd(hint string, defaultVal string, mask string) InputMsg {
|
||||||
return passwd(hint, defaultVal, "", true)
|
var ioBuf []byte
|
||||||
}
|
|
||||||
|
|
||||||
func PasswdResponseSignalWithMask(hint string, defaultVal string, mask string) InputMsg {
|
|
||||||
return passwd(hint, defaultVal, mask, true)
|
|
||||||
}
|
|
||||||
|
|
||||||
func MessageBoxRaw(hint string, defaultVal string) InputMsg {
|
|
||||||
return messageBox(hint, defaultVal)
|
|
||||||
}
|
|
||||||
|
|
||||||
func messageBox(hint string, defaultVal string) InputMsg {
|
|
||||||
var ioBuf []rune
|
|
||||||
if hint != "" {
|
if hint != "" {
|
||||||
fmt.Print(hint)
|
fmt.Print(hint)
|
||||||
}
|
}
|
||||||
if strings.Index(hint, "\n") >= 0 {
|
state, err := terminal.MakeRaw(int(os.Stdin.Fd()))
|
||||||
hint = strings.TrimSpace(hint[strings.LastIndex(hint, "\n"):])
|
|
||||||
}
|
|
||||||
fd := int(os.Stdin.Fd())
|
|
||||||
state, err := terminal.MakeRaw(fd)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return InputMsg{msg: "", err: err}
|
return InputMsg{"", err}
|
||||||
}
|
}
|
||||||
defer fmt.Println()
|
defer terminal.Restore(0, state)
|
||||||
defer terminal.Restore(fd, state)
|
|
||||||
inputReader := bufio.NewReader(os.Stdin)
|
inputReader := bufio.NewReader(os.Stdin)
|
||||||
for {
|
for {
|
||||||
b, _, err := inputReader.ReadRune()
|
b, err := inputReader.ReadByte()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return InputMsg{msg: "", err: err}
|
return InputMsg{"", err}
|
||||||
}
|
}
|
||||||
if b == 0x0d {
|
if b == 0x0d {
|
||||||
strValue := strings.TrimSpace(string(ioBuf))
|
fmt.Println()
|
||||||
if len(strValue) == 0 {
|
return InputMsg{strings.TrimSpace(string(ioBuf)), nil}
|
||||||
strValue = defaultVal
|
|
||||||
}
|
}
|
||||||
return InputMsg{msg: strValue, err: err}
|
if mask != "" {
|
||||||
}
|
|
||||||
if b == 0x08 || b == 0x7F {
|
|
||||||
if len(ioBuf) > 0 {
|
|
||||||
ioBuf = ioBuf[:len(ioBuf)-1]
|
|
||||||
}
|
|
||||||
fmt.Print("\r")
|
|
||||||
for i := 0; i < len(ioBuf)+2+len(hint); i++ {
|
|
||||||
fmt.Print(" ")
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
ioBuf = append(ioBuf, b)
|
|
||||||
}
|
|
||||||
fmt.Print("\r")
|
|
||||||
if hint != "" {
|
|
||||||
fmt.Print(hint)
|
|
||||||
}
|
|
||||||
fmt.Print(string(ioBuf))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func isSiganl(s rune) bool {
|
|
||||||
switch s {
|
|
||||||
case 0x03, 0x1a, 0x1c:
|
|
||||||
return true
|
|
||||||
default:
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func passwd(hint string, defaultVal string, mask string, handleSignal bool) InputMsg {
|
|
||||||
var ioBuf []rune
|
|
||||||
if hint != "" {
|
|
||||||
fmt.Print(hint)
|
|
||||||
}
|
|
||||||
if strings.Index(hint, "\n") >= 0 {
|
|
||||||
hint = strings.TrimSpace(hint[strings.LastIndex(hint, "\n"):])
|
|
||||||
}
|
|
||||||
fd := int(os.Stdin.Fd())
|
|
||||||
state, err := terminal.MakeRaw(fd)
|
|
||||||
if err != nil {
|
|
||||||
return InputMsg{msg: "", err: err}
|
|
||||||
}
|
|
||||||
defer fmt.Println()
|
|
||||||
defer terminal.Restore(fd, state)
|
|
||||||
inputReader := bufio.NewReader(os.Stdin)
|
|
||||||
for {
|
|
||||||
b, _, err := inputReader.ReadRune()
|
|
||||||
if err != nil {
|
|
||||||
return InputMsg{msg: "", err: err}
|
|
||||||
}
|
|
||||||
if handleSignal && isSiganl(b) {
|
|
||||||
if runtime.GOOS != "windows" {
|
|
||||||
terminal.Restore(fd, state)
|
|
||||||
}
|
|
||||||
if err := signal(b); err != nil {
|
|
||||||
return InputMsg{
|
|
||||||
msg: "",
|
|
||||||
err: err,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if b == 0x0d {
|
|
||||||
strValue := strings.TrimSpace(string(ioBuf))
|
|
||||||
if len(strValue) == 0 {
|
|
||||||
strValue = defaultVal
|
|
||||||
}
|
|
||||||
return InputMsg{msg: strValue, err: err}
|
|
||||||
}
|
|
||||||
if b == 0x08 || b == 0x7F {
|
|
||||||
if len(ioBuf) > 0 {
|
|
||||||
ioBuf = ioBuf[:len(ioBuf)-1]
|
|
||||||
}
|
|
||||||
fmt.Print("\r")
|
|
||||||
for i := 0; i < len(ioBuf)+2+len(hint); i++ {
|
|
||||||
fmt.Print(" ")
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
ioBuf = append(ioBuf, b)
|
|
||||||
}
|
|
||||||
fmt.Print("\r")
|
|
||||||
if hint != "" {
|
|
||||||
fmt.Print(hint)
|
|
||||||
}
|
|
||||||
for i := 0; i < len(ioBuf); i++ {
|
|
||||||
fmt.Print(mask)
|
fmt.Print(mask)
|
||||||
}
|
}
|
||||||
|
ioBuf = append(ioBuf, b)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -159,18 +57,9 @@ func MessageBox(hint string, defaultVal string) InputMsg {
|
|||||||
inputReader := bufio.NewReader(os.Stdin)
|
inputReader := bufio.NewReader(os.Stdin)
|
||||||
str, err := inputReader.ReadString('\n')
|
str, err := inputReader.ReadString('\n')
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return InputMsg{msg: str, err: err}
|
return InputMsg{"", err}
|
||||||
}
|
}
|
||||||
str = strings.TrimSpace(str)
|
return InputMsg{strings.TrimSpace(str), nil}
|
||||||
if len(str) == 0 {
|
|
||||||
str = defaultVal
|
|
||||||
}
|
|
||||||
return InputMsg{msg: str, err: err}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (im *InputMsg) IgnoreSliceParseError(i bool) *InputMsg {
|
|
||||||
im.skipSliceSigErr = i
|
|
||||||
return im
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (im InputMsg) String() (string, error) {
|
func (im InputMsg) String() (string, error) {
|
||||||
@ -185,38 +74,6 @@ func (im InputMsg) MustString() string {
|
|||||||
return res
|
return res
|
||||||
}
|
}
|
||||||
|
|
||||||
func (im InputMsg) SliceString(sep string) ([]string, error) {
|
|
||||||
if im.err != nil {
|
|
||||||
return nil, im.err
|
|
||||||
}
|
|
||||||
if len(strings.TrimSpace(im.msg)) == 0 {
|
|
||||||
return []string{}, nil
|
|
||||||
}
|
|
||||||
return strings.Split(im.msg, sep), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (im InputMsg) MustSliceString(sep string) []string {
|
|
||||||
res, _ := im.SliceString(sep)
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
func (im InputMsg) sliceFn(sep string, fn func(string) (interface{}, error)) ([]interface{}, error) {
|
|
||||||
var res []interface{}
|
|
||||||
data, err := im.SliceString(sep)
|
|
||||||
if err != nil {
|
|
||||||
return res, err
|
|
||||||
}
|
|
||||||
for _, v := range data {
|
|
||||||
code, err := fn(v)
|
|
||||||
if err != nil && !im.skipSliceSigErr {
|
|
||||||
return nil, err
|
|
||||||
} else if err == nil {
|
|
||||||
res = append(res, code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return res, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (im InputMsg) Int() (int, error) {
|
func (im InputMsg) Int() (int, error) {
|
||||||
if im.err != nil {
|
if im.err != nil {
|
||||||
return 0, im.err
|
return 0, im.err
|
||||||
@ -224,22 +81,6 @@ func (im InputMsg) Int() (int, error) {
|
|||||||
return strconv.Atoi(im.msg)
|
return strconv.Atoi(im.msg)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (im InputMsg) SliceInt(sep string) ([]int, error) {
|
|
||||||
data, err := im.sliceFn(sep, func(v string) (interface{}, error) {
|
|
||||||
return strconv.Atoi(v)
|
|
||||||
})
|
|
||||||
var res []int
|
|
||||||
for _, v := range data {
|
|
||||||
res = append(res, v.(int))
|
|
||||||
}
|
|
||||||
return res, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (im InputMsg) MustSliceInt(sep string) []int {
|
|
||||||
res, _ := im.SliceInt(sep)
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
func (im InputMsg) MustInt() int {
|
func (im InputMsg) MustInt() int {
|
||||||
res, _ := im.Int()
|
res, _ := im.Int()
|
||||||
return res
|
return res
|
||||||
@ -257,22 +98,6 @@ func (im InputMsg) MustInt64() int64 {
|
|||||||
return res
|
return res
|
||||||
}
|
}
|
||||||
|
|
||||||
func (im InputMsg) SliceInt64(sep string) ([]int64, error) {
|
|
||||||
data, err := im.sliceFn(sep, func(v string) (interface{}, error) {
|
|
||||||
return strconv.ParseInt(v, 10, 64)
|
|
||||||
})
|
|
||||||
var res []int64
|
|
||||||
for _, v := range data {
|
|
||||||
res = append(res, v.(int64))
|
|
||||||
}
|
|
||||||
return res, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (im InputMsg) MustSliceInt64(sep string) []int64 {
|
|
||||||
res, _ := im.SliceInt64(sep)
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
func (im InputMsg) Uint64() (uint64, error) {
|
func (im InputMsg) Uint64() (uint64, error) {
|
||||||
if im.err != nil {
|
if im.err != nil {
|
||||||
return 0, im.err
|
return 0, im.err
|
||||||
@ -284,21 +109,6 @@ func (im InputMsg) MustUint64() uint64 {
|
|||||||
res, _ := im.Uint64()
|
res, _ := im.Uint64()
|
||||||
return res
|
return res
|
||||||
}
|
}
|
||||||
func (im InputMsg) SliceUint64(sep string) ([]uint64, error) {
|
|
||||||
data, err := im.sliceFn(sep, func(v string) (interface{}, error) {
|
|
||||||
return strconv.ParseUint(v, 10, 64)
|
|
||||||
})
|
|
||||||
var res []uint64
|
|
||||||
for _, v := range data {
|
|
||||||
res = append(res, v.(uint64))
|
|
||||||
}
|
|
||||||
return res, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (im InputMsg) MustSliceUint64(sep string) []uint64 {
|
|
||||||
res, _ := im.SliceUint64(sep)
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
func (im InputMsg) Bool() (bool, error) {
|
func (im InputMsg) Bool() (bool, error) {
|
||||||
if im.err != nil {
|
if im.err != nil {
|
||||||
@ -312,22 +122,6 @@ func (im InputMsg) MustBool() bool {
|
|||||||
return res
|
return res
|
||||||
}
|
}
|
||||||
|
|
||||||
func (im InputMsg) SliceBool(sep string) ([]bool, error) {
|
|
||||||
data, err := im.sliceFn(sep, func(v string) (interface{}, error) {
|
|
||||||
return strconv.ParseBool(v)
|
|
||||||
})
|
|
||||||
var res []bool
|
|
||||||
for _, v := range data {
|
|
||||||
res = append(res, v.(bool))
|
|
||||||
}
|
|
||||||
return res, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (im InputMsg) MustSliceBool(sep string) []bool {
|
|
||||||
res, _ := im.SliceBool(sep)
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
func (im InputMsg) Float64() (float64, error) {
|
func (im InputMsg) Float64() (float64, error) {
|
||||||
if im.err != nil {
|
if im.err != nil {
|
||||||
return 0, im.err
|
return 0, im.err
|
||||||
@ -340,22 +134,6 @@ func (im InputMsg) MustFloat64() float64 {
|
|||||||
return res
|
return res
|
||||||
}
|
}
|
||||||
|
|
||||||
func (im InputMsg) SliceFloat64(sep string) ([]float64, error) {
|
|
||||||
data, err := im.sliceFn(sep, func(v string) (interface{}, error) {
|
|
||||||
return strconv.ParseFloat(v, 64)
|
|
||||||
})
|
|
||||||
var res []float64
|
|
||||||
for _, v := range data {
|
|
||||||
res = append(res, v.(float64))
|
|
||||||
}
|
|
||||||
return res, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (im InputMsg) MustSliceFloat64(sep string) []float64 {
|
|
||||||
res, _ := im.SliceFloat64(sep)
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
func (im InputMsg) Float32() (float32, error) {
|
func (im InputMsg) Float32() (float32, error) {
|
||||||
if im.err != nil {
|
if im.err != nil {
|
||||||
return 0, im.err
|
return 0, im.err
|
||||||
@ -369,24 +147,7 @@ func (im InputMsg) MustFloat32() float32 {
|
|||||||
return res
|
return res
|
||||||
}
|
}
|
||||||
|
|
||||||
func (im InputMsg) SliceFloat32(sep string) ([]float32, error) {
|
|
||||||
data, err := im.sliceFn(sep, func(v string) (interface{}, error) {
|
|
||||||
return strconv.ParseFloat(v, 32)
|
|
||||||
})
|
|
||||||
var res []float32
|
|
||||||
for _, v := range data {
|
|
||||||
res = append(res, v.(float32))
|
|
||||||
}
|
|
||||||
return res, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (im InputMsg) MustSliceFloat32(sep string) []float32 {
|
|
||||||
res, _ := im.SliceFloat32(sep)
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
func YesNo(hint string, defaults bool) bool {
|
func YesNo(hint string, defaults bool) bool {
|
||||||
for {
|
|
||||||
res := strings.ToUpper(MessageBox(hint, "").MustString())
|
res := strings.ToUpper(MessageBox(hint, "").MustString())
|
||||||
if res == "" {
|
if res == "" {
|
||||||
return defaults
|
return defaults
|
||||||
@ -396,36 +157,38 @@ func YesNo(hint string, defaults bool) bool {
|
|||||||
return true
|
return true
|
||||||
} else if res == "N" {
|
} else if res == "N" {
|
||||||
return false
|
return false
|
||||||
}
|
} else {
|
||||||
|
return defaults
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func StopUntil(hint string, trigger string, repeat bool) error {
|
func StopUntil(hint string, trigger string, repeat bool) error {
|
||||||
pressLen := len([]rune(trigger))
|
pressLen := len(trigger)
|
||||||
if trigger == "" {
|
if trigger == "" {
|
||||||
pressLen = 1
|
pressLen = 1
|
||||||
|
} else {
|
||||||
|
pressLen = len(trigger)
|
||||||
}
|
}
|
||||||
fd := int(os.Stdin.Fd())
|
state, err := terminal.MakeRaw(int(os.Stdin.Fd()))
|
||||||
if hint != "" {
|
|
||||||
fmt.Print(hint)
|
|
||||||
}
|
|
||||||
state, err := terminal.MakeRaw(fd)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
defer terminal.Restore(fd, state)
|
defer terminal.Restore(0, state)
|
||||||
inputReader := bufio.NewReader(os.Stdin)
|
inputReader := bufio.NewReader(os.Stdin)
|
||||||
//ioBuf := make([]byte, pressLen)
|
//ioBuf := make([]byte, pressLen)
|
||||||
|
if hint != "" && !repeat {
|
||||||
|
fmt.Print(hint)
|
||||||
|
}
|
||||||
i := 0
|
i := 0
|
||||||
for {
|
for {
|
||||||
b, _, err := inputReader.ReadRune()
|
b, err := inputReader.ReadByte()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if trigger == "" {
|
if trigger == "" {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
if b == []rune(trigger)[i] {
|
if b == trigger[i] {
|
||||||
i++
|
i++
|
||||||
if i == pressLen {
|
if i == pressLen {
|
||||||
break
|
break
|
||||||
@ -434,7 +197,7 @@ func StopUntil(hint string, trigger string, repeat bool) error {
|
|||||||
}
|
}
|
||||||
i = 0
|
i = 0
|
||||||
if hint != "" && repeat {
|
if hint != "" && repeat {
|
||||||
fmt.Print("\r\n")
|
fmt.Print("\n")
|
||||||
fmt.Print(hint)
|
fmt.Print(hint)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
49
io_test.go
49
io_test.go
@ -1,49 +0,0 @@
|
|||||||
package stario
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func Test_Slice(t *testing.T) {
|
|
||||||
var data = InputMsg{
|
|
||||||
msg: "true,false,true,true,false,0,1,hello",
|
|
||||||
err: nil,
|
|
||||||
skipSliceSigErr: false,
|
|
||||||
}
|
|
||||||
res, err := data.IgnoreSliceParseError(true).SliceBool(",")
|
|
||||||
if err != nil {
|
|
||||||
fmt.Println(res)
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if len(res) == 0 {
|
|
||||||
t.Fatal(res)
|
|
||||||
}
|
|
||||||
fmt.Println(res)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSliceMsg(t *testing.T) {
|
|
||||||
var data = InputMsg{
|
|
||||||
msg: "",
|
|
||||||
err: nil,
|
|
||||||
skipSliceSigErr: false,
|
|
||||||
}
|
|
||||||
res, err := data.SliceString(",")
|
|
||||||
if err != nil {
|
|
||||||
fmt.Println(res)
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if len(res) != 0 {
|
|
||||||
t.Fatal(res)
|
|
||||||
}
|
|
||||||
fmt.Println(len(res))
|
|
||||||
res2, err := data.SliceInt64(",")
|
|
||||||
if err != nil {
|
|
||||||
fmt.Println(res2)
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if len(res2) != 0 {
|
|
||||||
t.Fatal(res2)
|
|
||||||
}
|
|
||||||
fmt.Println(len(res2))
|
|
||||||
}
|
|
325
que.go
325
que.go
@ -1,325 +0,0 @@
|
|||||||
package stario
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"encoding/binary"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
var ErrDeadlineExceeded error = errors.New("deadline exceeded")
|
|
||||||
|
|
||||||
// 识别头
|
|
||||||
var header = []byte{11, 27, 19, 96, 12, 25, 02, 20}
|
|
||||||
|
|
||||||
// MsgQueue 为基本的信息单位
|
|
||||||
type MsgQueue struct {
|
|
||||||
ID uint16
|
|
||||||
Msg []byte
|
|
||||||
Conn interface{}
|
|
||||||
}
|
|
||||||
|
|
||||||
// StarQueue 为流数据中的消息队列分发
|
|
||||||
type StarQueue struct {
|
|
||||||
maxLength uint32
|
|
||||||
count int64
|
|
||||||
Encode bool
|
|
||||||
msgID uint16
|
|
||||||
msgPool chan MsgQueue
|
|
||||||
unFinMsg sync.Map
|
|
||||||
lastID int //= -1
|
|
||||||
ctx context.Context
|
|
||||||
cancel context.CancelFunc
|
|
||||||
duration time.Duration
|
|
||||||
EncodeFunc func([]byte) []byte
|
|
||||||
DecodeFunc func([]byte) []byte
|
|
||||||
//restoreMu sync.Mutex
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewQueueCtx(ctx context.Context, count int64, maxMsgLength uint32) *StarQueue {
|
|
||||||
var q StarQueue
|
|
||||||
q.Encode = false
|
|
||||||
q.count = count
|
|
||||||
q.maxLength = maxMsgLength
|
|
||||||
q.msgPool = make(chan MsgQueue, count)
|
|
||||||
if ctx == nil {
|
|
||||||
q.ctx, q.cancel = context.WithCancel(context.Background())
|
|
||||||
} else {
|
|
||||||
q.ctx, q.cancel = context.WithCancel(ctx)
|
|
||||||
}
|
|
||||||
q.duration = 0
|
|
||||||
return &q
|
|
||||||
}
|
|
||||||
func NewQueueWithCount(count int64) *StarQueue {
|
|
||||||
return NewQueueCtx(nil, count, 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewQueue 建立一个新消息队列
|
|
||||||
func NewQueue() *StarQueue {
|
|
||||||
return NewQueueWithCount(32)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Uint32ToByte 4位uint32转byte
|
|
||||||
func Uint32ToByte(src uint32) []byte {
|
|
||||||
res := make([]byte, 4)
|
|
||||||
res[3] = uint8(src)
|
|
||||||
res[2] = uint8(src >> 8)
|
|
||||||
res[1] = uint8(src >> 16)
|
|
||||||
res[0] = uint8(src >> 24)
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
// ByteToUint32 byte转4位uint32
|
|
||||||
func ByteToUint32(src []byte) uint32 {
|
|
||||||
var res uint32
|
|
||||||
buffer := bytes.NewBuffer(src)
|
|
||||||
binary.Read(buffer, binary.BigEndian, &res)
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
// Uint16ToByte 2位uint16转byte
|
|
||||||
func Uint16ToByte(src uint16) []byte {
|
|
||||||
res := make([]byte, 2)
|
|
||||||
res[1] = uint8(src)
|
|
||||||
res[0] = uint8(src >> 8)
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
// ByteToUint16 用于byte转uint16
|
|
||||||
func ByteToUint16(src []byte) uint16 {
|
|
||||||
var res uint16
|
|
||||||
buffer := bytes.NewBuffer(src)
|
|
||||||
binary.Read(buffer, binary.BigEndian, &res)
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
// BuildMessage 生成编码后的信息用于发送
|
|
||||||
func (q *StarQueue) BuildMessage(src []byte) []byte {
|
|
||||||
var buff bytes.Buffer
|
|
||||||
q.msgID++
|
|
||||||
if q.Encode {
|
|
||||||
src = q.EncodeFunc(src)
|
|
||||||
}
|
|
||||||
length := uint32(len(src))
|
|
||||||
buff.Write(header)
|
|
||||||
buff.Write(Uint32ToByte(length))
|
|
||||||
buff.Write(Uint16ToByte(q.msgID))
|
|
||||||
buff.Write(src)
|
|
||||||
return buff.Bytes()
|
|
||||||
}
|
|
||||||
|
|
||||||
// BuildHeader 生成编码后的Header用于发送
|
|
||||||
func (q *StarQueue) BuildHeader(length uint32) []byte {
|
|
||||||
var buff bytes.Buffer
|
|
||||||
q.msgID++
|
|
||||||
buff.Write(header)
|
|
||||||
buff.Write(Uint32ToByte(length))
|
|
||||||
buff.Write(Uint16ToByte(q.msgID))
|
|
||||||
return buff.Bytes()
|
|
||||||
}
|
|
||||||
|
|
||||||
type unFinMsg struct {
|
|
||||||
ID uint16
|
|
||||||
LengthRecv uint32
|
|
||||||
// HeaderMsg 信息头,应当为14位:8位识别码+4位长度码+2位id
|
|
||||||
HeaderMsg []byte
|
|
||||||
RecvMsg []byte
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *StarQueue) push2list(msg MsgQueue) {
|
|
||||||
q.msgPool <- msg
|
|
||||||
}
|
|
||||||
|
|
||||||
// ParseMessage 用于解析收到的msg信息
|
|
||||||
func (q *StarQueue) ParseMessage(msg []byte, conn interface{}) error {
|
|
||||||
return q.parseMessage(msg, conn)
|
|
||||||
}
|
|
||||||
|
|
||||||
// parseMessage 用于解析收到的msg信息
|
|
||||||
func (q *StarQueue) parseMessage(msg []byte, conn interface{}) error {
|
|
||||||
tmp, ok := q.unFinMsg.Load(conn)
|
|
||||||
if ok { //存在未完成的信息
|
|
||||||
lastMsg := tmp.(*unFinMsg)
|
|
||||||
headerLen := len(lastMsg.HeaderMsg)
|
|
||||||
if headerLen < 14 { //未完成头标题
|
|
||||||
//传输的数据不能填充header头
|
|
||||||
if len(msg) < 14-headerLen {
|
|
||||||
//加入header头并退出
|
|
||||||
lastMsg.HeaderMsg = bytesMerge(lastMsg.HeaderMsg, msg)
|
|
||||||
q.unFinMsg.Store(conn, lastMsg)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
//获取14字节完整的header
|
|
||||||
header := msg[0 : 14-headerLen]
|
|
||||||
lastMsg.HeaderMsg = bytesMerge(lastMsg.HeaderMsg, header)
|
|
||||||
//检查收到的header是否为认证header
|
|
||||||
//若不是,丢弃并重新来过
|
|
||||||
if !checkHeader(lastMsg.HeaderMsg[0:8]) {
|
|
||||||
q.unFinMsg.Delete(conn)
|
|
||||||
if len(msg) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return q.parseMessage(msg, conn)
|
|
||||||
}
|
|
||||||
//获得本数据包长度
|
|
||||||
lastMsg.LengthRecv = ByteToUint32(lastMsg.HeaderMsg[8:12])
|
|
||||||
if q.maxLength != 0 && lastMsg.LengthRecv > q.maxLength {
|
|
||||||
q.unFinMsg.Delete(conn)
|
|
||||||
return fmt.Errorf("msg length is %d ,too large than %d", lastMsg.LengthRecv, q.maxLength)
|
|
||||||
}
|
|
||||||
//获得本数据包ID
|
|
||||||
lastMsg.ID = ByteToUint16(lastMsg.HeaderMsg[12:14])
|
|
||||||
//存入列表
|
|
||||||
q.unFinMsg.Store(conn, lastMsg)
|
|
||||||
msg = msg[14-headerLen:]
|
|
||||||
if uint32(len(msg)) < lastMsg.LengthRecv {
|
|
||||||
lastMsg.RecvMsg = msg
|
|
||||||
q.unFinMsg.Store(conn, lastMsg)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if uint32(len(msg)) >= lastMsg.LengthRecv {
|
|
||||||
lastMsg.RecvMsg = msg[0:lastMsg.LengthRecv]
|
|
||||||
if q.Encode {
|
|
||||||
lastMsg.RecvMsg = q.DecodeFunc(lastMsg.RecvMsg)
|
|
||||||
}
|
|
||||||
msg = msg[lastMsg.LengthRecv:]
|
|
||||||
storeMsg := MsgQueue{
|
|
||||||
ID: lastMsg.ID,
|
|
||||||
Msg: lastMsg.RecvMsg,
|
|
||||||
Conn: conn,
|
|
||||||
}
|
|
||||||
//q.restoreMu.Lock()
|
|
||||||
q.push2list(storeMsg)
|
|
||||||
//q.restoreMu.Unlock()
|
|
||||||
q.unFinMsg.Delete(conn)
|
|
||||||
return q.parseMessage(msg, conn)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
lastID := int(lastMsg.LengthRecv) - len(lastMsg.RecvMsg)
|
|
||||||
if lastID < 0 {
|
|
||||||
q.unFinMsg.Delete(conn)
|
|
||||||
return q.parseMessage(msg, conn)
|
|
||||||
}
|
|
||||||
if len(msg) >= lastID {
|
|
||||||
lastMsg.RecvMsg = bytesMerge(lastMsg.RecvMsg, msg[0:lastID])
|
|
||||||
if q.Encode {
|
|
||||||
lastMsg.RecvMsg = q.DecodeFunc(lastMsg.RecvMsg)
|
|
||||||
}
|
|
||||||
storeMsg := MsgQueue{
|
|
||||||
ID: lastMsg.ID,
|
|
||||||
Msg: lastMsg.RecvMsg,
|
|
||||||
Conn: conn,
|
|
||||||
}
|
|
||||||
q.push2list(storeMsg)
|
|
||||||
q.unFinMsg.Delete(conn)
|
|
||||||
if len(msg) == lastID {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
msg = msg[lastID:]
|
|
||||||
return q.parseMessage(msg, conn)
|
|
||||||
}
|
|
||||||
lastMsg.RecvMsg = bytesMerge(lastMsg.RecvMsg, msg)
|
|
||||||
q.unFinMsg.Store(conn, lastMsg)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(msg) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
var start int
|
|
||||||
if start = searchHeader(msg); start == -1 {
|
|
||||||
return errors.New("data format error")
|
|
||||||
}
|
|
||||||
msg = msg[start:]
|
|
||||||
lastMsg := unFinMsg{}
|
|
||||||
q.unFinMsg.Store(conn, &lastMsg)
|
|
||||||
return q.parseMessage(msg, conn)
|
|
||||||
}
|
|
||||||
|
|
||||||
func checkHeader(msg []byte) bool {
|
|
||||||
if len(msg) != 8 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
for k, v := range msg {
|
|
||||||
if v != header[k] {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func searchHeader(msg []byte) int {
|
|
||||||
if len(msg) < 8 {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
for k, v := range msg {
|
|
||||||
find := 0
|
|
||||||
if v == header[0] {
|
|
||||||
for k2, v2 := range header {
|
|
||||||
if msg[k+k2] == v2 {
|
|
||||||
find++
|
|
||||||
} else {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if find == 8 {
|
|
||||||
return k
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return -1
|
|
||||||
}
|
|
||||||
|
|
||||||
func bytesMerge(src ...[]byte) []byte {
|
|
||||||
var buff bytes.Buffer
|
|
||||||
for _, v := range src {
|
|
||||||
buff.Write(v)
|
|
||||||
}
|
|
||||||
return buff.Bytes()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Restore 获取收到的信息
|
|
||||||
func (q *StarQueue) Restore() (MsgQueue, error) {
|
|
||||||
if q.duration.Seconds() == 0 {
|
|
||||||
q.duration = 86400 * time.Second
|
|
||||||
}
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-q.ctx.Done():
|
|
||||||
return MsgQueue{}, errors.New("Stoped By External Function Call")
|
|
||||||
case <-time.After(q.duration):
|
|
||||||
if q.duration != 0 {
|
|
||||||
return MsgQueue{}, ErrDeadlineExceeded
|
|
||||||
}
|
|
||||||
case data, ok := <-q.msgPool:
|
|
||||||
if !ok {
|
|
||||||
return MsgQueue{}, os.ErrClosed
|
|
||||||
}
|
|
||||||
return data, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// RestoreOne 获取收到的一个信息
|
|
||||||
// 兼容性修改
|
|
||||||
func (q *StarQueue) RestoreOne() (MsgQueue, error) {
|
|
||||||
return q.Restore()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Stop 立即停止Restore
|
|
||||||
func (q *StarQueue) Stop() {
|
|
||||||
q.cancel()
|
|
||||||
}
|
|
||||||
|
|
||||||
// RestoreDuration Restore最大超时时间
|
|
||||||
func (q *StarQueue) RestoreDuration(tm time.Duration) {
|
|
||||||
q.duration = tm
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *StarQueue) RestoreChan() <-chan MsgQueue {
|
|
||||||
return q.msgPool
|
|
||||||
}
|
|
42
que_test.go
42
que_test.go
@ -1,42 +0,0 @@
|
|||||||
package stario
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func Test_QueSpeed(t *testing.T) {
|
|
||||||
que := NewQueueWithCount(0)
|
|
||||||
stop := make(chan struct{}, 1)
|
|
||||||
que.RestoreDuration(time.Second * 10)
|
|
||||||
var count int64
|
|
||||||
go func() {
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-stop:
|
|
||||||
//fmt.Println(count)
|
|
||||||
return
|
|
||||||
default:
|
|
||||||
}
|
|
||||||
_, err := que.RestoreOne()
|
|
||||||
if err == nil {
|
|
||||||
count++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
cp := 0
|
|
||||||
stoped := time.After(time.Second * 10)
|
|
||||||
data := que.BuildMessage([]byte("hello"))
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-stoped:
|
|
||||||
fmt.Println(count, cp)
|
|
||||||
stop <- struct{}{}
|
|
||||||
return
|
|
||||||
default:
|
|
||||||
que.ParseMessage(data, "lala")
|
|
||||||
cp++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,22 +0,0 @@
|
|||||||
//go:build windows
|
|
||||||
// +build windows
|
|
||||||
|
|
||||||
package stario
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
func signal(sigtype rune) error {
|
|
||||||
//todo: use win32api call signal
|
|
||||||
switch sigtype {
|
|
||||||
case 0x03:
|
|
||||||
return errors.New("SIGNAL SIGINT RECIVED")
|
|
||||||
case 0x1a:
|
|
||||||
return errors.New("SIGNAL SIGSTOP RECIVED")
|
|
||||||
case 0x1c:
|
|
||||||
return errors.New("SIGNAL SIGQUIT RECIVED")
|
|
||||||
default:
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,26 +0,0 @@
|
|||||||
//go:build !windows
|
|
||||||
// +build !windows
|
|
||||||
|
|
||||||
package stario
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"os"
|
|
||||||
"syscall"
|
|
||||||
)
|
|
||||||
|
|
||||||
func signal(sigtype rune) error {
|
|
||||||
switch sigtype {
|
|
||||||
case 0x03:
|
|
||||||
syscall.Kill(os.Getpid(), syscall.SIGINT)
|
|
||||||
return errors.New("SIGNAL SIGINT RECIVED")
|
|
||||||
case 0x1a:
|
|
||||||
syscall.Kill(os.Getpid(), syscall.SIGSTOP)
|
|
||||||
return errors.New("SIGNAL SIGSTOP RECIVED")
|
|
||||||
case 0x1c:
|
|
||||||
syscall.Kill(os.Getpid(), syscall.SIGQUIT)
|
|
||||||
return errors.New("SIGNAL SIGQUIT RECIVED")
|
|
||||||
default:
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
55
sync.go
55
sync.go
@ -1,55 +0,0 @@
|
|||||||
package stario
|
|
||||||
|
|
||||||
import (
|
|
||||||
"sync"
|
|
||||||
"sync/atomic"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type WaitGroup struct {
|
|
||||||
wg *sync.WaitGroup
|
|
||||||
maxCount uint32
|
|
||||||
allCount uint32
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewWaitGroup(maxCount int) WaitGroup {
|
|
||||||
return WaitGroup{wg: &sync.WaitGroup{}, maxCount: uint32(maxCount)}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *WaitGroup) Add(delta int) {
|
|
||||||
var Udelta uint32
|
|
||||||
if delta < 0 {
|
|
||||||
Udelta = uint32(-delta - 1)
|
|
||||||
} else {
|
|
||||||
Udelta = uint32(delta)
|
|
||||||
}
|
|
||||||
for {
|
|
||||||
allC := atomic.LoadUint32(&w.allCount)
|
|
||||||
if atomic.LoadUint32(&w.maxCount) == 0 || atomic.LoadUint32(&w.maxCount) >= allC+uint32(delta) {
|
|
||||||
if delta < 0 {
|
|
||||||
atomic.AddUint32(&w.allCount, ^uint32(Udelta))
|
|
||||||
} else {
|
|
||||||
atomic.AddUint32(&w.allCount, uint32(Udelta))
|
|
||||||
}
|
|
||||||
break
|
|
||||||
}
|
|
||||||
time.Sleep(time.Microsecond)
|
|
||||||
}
|
|
||||||
w.wg.Add(delta)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *WaitGroup) Done() {
|
|
||||||
w.Add(-1)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *WaitGroup) Wait() {
|
|
||||||
w.wg.Wait()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *WaitGroup) GetMaxWaitNum() int {
|
|
||||||
return int(atomic.LoadUint32(&w.maxCount))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *WaitGroup) SetMaxWaitNum(num int) {
|
|
||||||
atomic.AddUint32(&w.maxCount, uint32(num))
|
|
||||||
}
|
|
Loading…
x
Reference in New Issue
Block a user