chore: rule-provider direct using IndexByte in bytes for find new line

This commit is contained in:
wwqgtxx 2023-04-01 16:55:02 +08:00
parent 9d7a78e1ef
commit 9442880a5a

View file

@ -1,12 +1,10 @@
package provider package provider
import ( import (
"bufio"
"bytes" "bytes"
"encoding/json" "encoding/json"
"errors" "errors"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
"io"
"runtime" "runtime"
"time" "time"
@ -161,36 +159,30 @@ func rulesParse(buf []byte, strategy ruleStrategy) (any, error) {
schema := &RulePayload{} schema := &RulePayload{}
reader := bufio.NewReader(bytes.NewReader(buf))
firstLineBuffer := pool.GetBuffer() firstLineBuffer := pool.GetBuffer()
defer pool.PutBuffer(firstLineBuffer) defer pool.PutBuffer(firstLineBuffer)
firstLineLength := 0 firstLineLength := 0
for { s := 0 // search start index
line, isPrefix, err := reader.ReadLine() for s < len(buf) {
if err != nil { // search buffer for a new line.
if err == io.EOF { line := buf[s:]
if firstLineLength == 0 { // find payload head if i := bytes.IndexByte(line, '\n'); i >= 0 {
i += s
line = buf[s : i+1]
s = i + 1
} else {
s = len(buf) // stop loop in next step
if firstLineLength == 0 { // no head or only one line body
return nil, ErrNoPayload return nil, ErrNoPayload
} }
break
}
return nil, err
}
firstLineBuffer.Write(line) // need a copy because the returned buffer is only valid until the next call to ReadLine
if isPrefix {
// If the line was too long for the buffer then isPrefix is set and the
// beginning of the line is returned. The rest of the line will be returned
// from future calls.
continue
} }
firstLineBuffer.Write(line)
if firstLineLength == 0 { // find payload head if firstLineLength == 0 { // find payload head
firstLineBuffer.WriteByte('\n')
firstLineLength = firstLineBuffer.Len() firstLineLength = firstLineBuffer.Len()
firstLineBuffer.WriteString(" - ''") // a test line firstLineBuffer.WriteString(" - ''") // a test line
err = yaml.Unmarshal(firstLineBuffer.Bytes(), schema) err := yaml.Unmarshal(firstLineBuffer.Bytes(), schema)
firstLineBuffer.Truncate(firstLineLength) firstLineBuffer.Truncate(firstLineLength)
if err == nil && (len(schema.Rules) > 0 || len(schema.Payload) > 0) { // found if err == nil && (len(schema.Rules) > 0 || len(schema.Payload) > 0) { // found
continue continue
@ -203,7 +195,7 @@ func rulesParse(buf []byte, strategy ruleStrategy) (any, error) {
} }
// parse payload body // parse payload body
err = yaml.Unmarshal(firstLineBuffer.Bytes(), schema) err := yaml.Unmarshal(firstLineBuffer.Bytes(), schema)
firstLineBuffer.Truncate(firstLineLength) firstLineBuffer.Truncate(firstLineLength)
if err != nil { if err != nil {
continue continue