github.com/vanus-labs/vanus/lib@v0.0.0-20231221070800-1334a7b9605e/json/parse/number.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 parse 16 17 import ( 18 // standard libraries. 19 "errors" 20 "io" 21 22 // this project. 23 "github.com/vanus-labs/vanus/lib/bytes" 24 ) 25 26 var errInvalidInteger = errors.New("invalid integer") 27 28 func IsDigit(c byte) bool { 29 return c >= '0' && c <= '9' 30 } 31 32 func ConsumeDigits(r io.ByteReader, w io.ByteWriter) (int, byte, error) { 33 return bytes.ConsumeUntil(r, w, func(c byte) bool { 34 return !IsDigit(c) 35 }) 36 } 37 38 func ExpectIntegerExt(c byte, s io.ByteScanner) (int, error) { 39 if c == '0' { 40 return 0, nil 41 } 42 43 var err error 44 sign := 1 45 if c == '-' { 46 sign = -1 47 c, err = s.ReadByte() 48 if err != nil { 49 return 0, errInvalidInteger 50 } 51 } 52 53 if c < '1' || c > '9' { 54 return 0, errInvalidInteger 55 } 56 num := int(c - '0') 57 58 for { 59 c, err = s.ReadByte() 60 if err != nil { 61 if err == io.EOF { //nolint:errorlint // io.EOF is not an error. 62 return sign * num, nil 63 } 64 return 0, err 65 } 66 67 if !IsDigit(c) { 68 return sign * num, s.UnreadByte() 69 } 70 71 // TODO(james.yin): check overflow 72 73 num = num*10 + int(c-'0') //nolint:gomnd // 10 is base 74 } 75 }