github.com/vanus-labs/vanus/lib@v0.0.0-20231221070800-1334a7b9605e/bytes/parse.go (about) 1 // Copyright 2023 Linkall Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package bytes 16 17 import ( 18 // standard libraries. 19 "errors" 20 "io" 21 ) 22 23 var errUnexpectedChar = errors.New("unexpected character") 24 25 func ExpectChar(r io.ByteReader, c byte) error { 26 b, err := r.ReadByte() 27 if err != nil || b != c { 28 return errUnexpectedChar 29 } 30 return nil 31 } 32 33 func ConsumeUntil(r io.ByteReader, w io.ByteWriter, stop func(byte) bool) (int, byte, error) { 34 for count := 0; ; count++ { 35 c, err := r.ReadByte() 36 if err != nil { 37 return count, 0, err 38 } 39 if stop(c) { 40 return count, c, nil 41 } 42 if err = w.WriteByte(c); err != nil { 43 return count, c, err 44 } 45 } 46 } 47 48 func Skip(r io.ByteReader, expect func(byte) bool) (int, byte, error) { 49 for count := 0; ; count++ { 50 c, err := r.ReadByte() 51 if err != nil { 52 return count, 0, err 53 } 54 if !expect(c) { 55 return count, c, nil 56 } 57 } 58 } 59 60 func IgnoreCount(_ int, c byte, err error) (byte, error) { 61 return c, err 62 } 63 64 func AcceptEOF(count int, c byte, err error) (int, bool, byte, error) { 65 switch { 66 case err == nil: 67 return count, false, c, nil 68 case err == io.EOF: //nolint:errorlint // io.EOF is not an error 69 return count, true, 0, nil 70 default: 71 return 0, false, 0, err 72 } 73 } 74 75 func Unread(r io.ByteScanner, eof bool, err error) error { 76 if err == nil && !eof { 77 err = r.UnreadByte() 78 } 79 return err 80 }