Skip to content

Commit

Permalink
优化
Browse files Browse the repository at this point in the history
  • Loading branch information
injoyai committed Dec 29, 2023
1 parent f47e307 commit ce8cddc
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 20 deletions.
7 changes: 5 additions & 2 deletions buf/buf_read_func_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ func TestReadPrefix(t *testing.T) {
t.Error(err)
}
t.Log(hex.EncodeToString(bs))
t.Log(ReadWithAll(buf))

bs, err = ReadWithAll(buf)
if err != nil {
t.Error(err)
}
t.Log(hex.EncodeToString(bs))
}
42 changes: 24 additions & 18 deletions io_func.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@ package io

import (
"bufio"
"bytes"
"io"
)

// NewMessageReader Reader转MessageReader
func NewMessageReader(r io.Reader, read ReadFunc) MessageReader {
return &messageReader{bufio.NewReader(r), read}
}

// DealMessageReader 处理MessageReader
func DealMessageReader(r MessageReader, fn DealFunc) error {
for {
bs, err := r.ReadMessage()
Expand All @@ -21,6 +24,7 @@ func DealMessageReader(r MessageReader, fn DealFunc) error {
}
}

// DealReader 处理Reader
func DealReader(r io.Reader, fn func(buf *bufio.Reader) error) (err error) {
buf := bufio.NewReader(r)
for ; err == nil; err = fn(buf) {
Expand All @@ -29,28 +33,30 @@ func DealReader(r io.Reader, fn func(buf *bufio.Reader) error) (err error) {
}

// ReadPrefix 读取Reader符合的头部,返回成功(nil),或者错误
func ReadPrefix(r Reader, prefix []byte) (int, error) {
length := 0
i := 0
loop:
for {
for ; i < len(prefix); i++ {
b := make([]byte, 1)
if _, err := io.ReadAtLeast(r, b, 1); err != nil {
return length, err
}
length++
if b[0] != prefix[i] {
if b[0] == prefix[0] {
i = 1
} else {
i = 0
func ReadPrefix(r Reader, prefix []byte) ([]byte, error) {
cache := []byte(nil)
for index := 0; index < len(prefix); {
b, err := ReadByte(r)
if err != nil {
return cache, err
}
cache = append(cache, b)
if b == prefix[index] {
index++
} else {
for len(cache) > 0 {
//only one error in this ReadPrefix ,it is EOF,and not important
cache2, _ := ReadPrefix(bytes.NewReader(cache[1:]), prefix)
if len(cache2) > 0 {
cache = cache2
break
}
continue loop
cache = cache[1:]
}
index = len(cache)
}
return length, nil
}
return cache, nil
}

// ReadByte 读取一字节
Expand Down
3 changes: 3 additions & 0 deletions io_func_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,7 @@ func TestReadPrefix(t *testing.T) {
t.Log(ReadPrefix(r, []byte("llo"))) //EOF
t.Log(ReadPrefix(r, []byte("aaa"))) //EOF
t.Log(ReadPrefix(r, []byte("aaa"))) //EOF
r = bytes.NewReader([]byte("hello world woworld"))
t.Log(ReadPrefix(r, []byte("lo"))) //lo nil
t.Log(ReadPrefix(r, []byte("lo"))) // EOF
}

0 comments on commit ce8cddc

Please sign in to comment.