// Converts numberToParse to a form that we can parse and write it to
// nationalNumber if it is written in RFC3966; otherwise extract a possible
// number out of it and write to nationalNumber.
437616
func buildNationalNumberForParsing(
	numberToParse string,
	nationalNumber *builder.Builder) {

	indexOfPhoneContext := strings.Index(numberToParse, RFC3966_PHONE_CONTEXT)
	if indexOfPhoneContext > 0 {
		phoneContextStart := indexOfPhoneContext + len(RFC3966_PHONE_CONTEXT)
		// If the phone context contains a phone number prefix, we need
		// to capture it, whereas domains will be ignored.
		if numberToParse[phoneContextStart] == PLUS_SIGN {
			// Additional parameters might follow the phone context. If so,
			// we will remove them here because the parameters after phone
			// context are not important for parsing the phone number.
			phoneContextEnd := strings.Index(numberToParse[phoneContextStart:], ";")
			if phoneContextEnd > 0 {
				nationalNumber.WriteString(
					numberToParse[phoneContextStart:phoneContextEnd])
			} else {
				nationalNumber.WriteString(numberToParse[phoneContextStart:])
			}
		}
		// Now append everything between the "tel:" prefix and the
		// phone-context. This should include the national number, an
		// optional extension or isdn-subaddress component. Note we also
		// handle the case when "tel:" is missing, as we have seen in some
		// of the phone number inputs. In that case, we append everything
		// from the beginning.
		indexOfRfc3966Prefix := strings.Index(numberToParse, RFC3966_PREFIX)
		indexOfNationalNumber := 0
		if indexOfRfc3966Prefix >= 0 {
			indexOfNationalNumber = indexOfRfc3966Prefix + len(RFC3966_PREFIX)
		}
		nationalNumber.WriteString(
			numberToParse[indexOfNationalNumber:indexOfPhoneContext])
	} else {
		// Extract a possible number from the string passed in (this
		// strips leading characters that could not be the start of a
		// phone number.)
		nationalNumber.WriteString(extractPossibleNumber(numberToParse))
	}

	// Delete the isdn-subaddress and everything after it if it is present.
	// Note extension won't appear at the same time with isdn-subaddress
	// according to paragraph 5.3 of the RFC3966 spec,
	indexOfIsdn := strings.Index(nationalNumber.String(), RFC3966_ISDN_SUBADDRESS)
	if indexOfIsdn > 0 {
		natNumBytes := nationalNumber.Bytes()
		nationalNumber.ResetWith(natNumBytes[:indexOfIsdn])
	}
	// If both phone context and isdn-subaddress are absent but other
	// parameters are present, the parameters are left in nationalNumber.
	// This is because we are concerned about deleting content from a
	// potential number string when there is no strong evidence that the
	// number is actually written in RFC3966.
}
711296
func formatNsnUsingPatternWithCarrier(
	nationalNumber string,
	formattingPattern *NumberFormat,
	numberFormat PhoneNumberFormat,
	carrierCode string) string {

	numberFormatRule := formattingPattern.GetFormat()
	m, ok := readFromRegexCache(formattingPattern.GetPattern())
	if !ok {
		pat := formattingPattern.GetPattern()
		m = regexp.MustCompile(pat)
		writeToRegexCache(pat, m)
	}

	formattedNationalNumber := ""
	if numberFormat == NATIONAL &&
		len(carrierCode) > 0 &&
		len(formattingPattern.GetDomesticCarrierCodeFormattingRule()) > 0 {
		// Replace the $CC in the formatting rule with the desired carrier code.
		carrierCodeFormattingRule := formattingPattern.GetDomesticCarrierCodeFormattingRule()
		i := 1
		carrierCodeFormattingRule =
			CC_PATTERN.ReplaceAllStringFunc(carrierCodeFormattingRule,
				func(s string) string {
					if i > 0 {
						i -= 1
						return carrierCode
					}
					return s
				})
		// Now replace the $FG in the formatting rule with the first group
		// and the carrier code combined in the appropriate way.
		i = 1
		numberFormatRule = FIRST_GROUP_PATTERN.ReplaceAllStringFunc(
			numberFormatRule,
			func(s string) string {
				if i > 0 {
					i -= 1
					return carrierCodeFormattingRule
				}
				return s
			})
		formattedNationalNumber = m.ReplaceAllString(numberFormatRule, nationalNumber)
	} else {
		// Use the national prefix formatting rule instead.
		nationalPrefixFormattingRule :=
			formattingPattern.GetNationalPrefixFormattingRule()
		if numberFormat == NATIONAL &&
			len(nationalPrefixFormattingRule) > 0 {
			i := 1
			fgp := FIRST_GROUP_PATTERN.ReplaceAllStringFunc(numberFormatRule,
				func(s string) string {
					if i > 0 {
						i -= 1
						return nationalPrefixFormattingRule
					}
					return s
				})
			formattedNationalNumber = m.ReplaceAllString(nationalNumber, fgp)
		} else {
			formattedNationalNumber = m.ReplaceAllString(
				nationalNumber,
				numberFormatRule,
			)
		}
	}
	if numberFormat == RFC3966 {
		// Strip any leading punctuation.
		inds := SEPARATOR_PATTERN.FindStringIndex(formattedNationalNumber)
		if len(inds) > 0 && inds[0] == 0 {
			formattedNationalNumber = formattedNationalNumber[inds[1]:]
		}
		allStr := NOT_SEPARATOR_PATTERN.FindAllString(formattedNationalNumber, -1)
		formattedNationalNumber = strings.Join(allStr, "-")
	}
	return formattedNationalNumber
}
916182
func nsToPID(ns string) (int, error) {
	// Make sure ns is well formed
	ok := strings.HasPrefix(ns, "/proc/")
	if !ok {
		return -1, fmt.Errorf("invalid nw name space: %v", ns)
	}

	elements := strings.Split(ns, "/")
	return strconv.Atoi(elements[2])
}
1160920
func (s *SubnetCommandBase) CheckNumArgs(args []string, errors []error) error {
	for num, err := range errors {
		if len(args) == num {
			return err
		}
	}
	return nil
}
1016484
func BuildNumeric(val string) (n Value, err error) {
	if val[0] == '-' || val[0] == '+' {
		signed, err := strconv.ParseInt(val, 0, 64)
		if err != nil {
			return Value{}, err
		}
		n = Value{Numeric(strconv.AppendInt(nil, signed, 10))}
	} else {
		unsigned, err := strconv.ParseUint(val, 0, 64)
		if err != nil {
			return Value{}, err
		}
		n = Value{Numeric(strconv.AppendUint(nil, unsigned, 10))}
	}
	return n, nil
}
1067042
func (f *formatter) formatNumeric(b []byte, x int64) {
	if fitsInBase256(len(b), x) {
		for i := len(b) - 1; i >= 0; i-- {
			b[i] = byte(x)
			x >>= 8
		}
		b[0] |= 0x80 // Highest bit indicates binary format
		return
	}

	f.formatOctal(b, 0) // Last resort, just write zero
	f.err = ErrFieldTooLong
}
1244059
func resultErrorFormatNumber(n float64) string {

	if isFloat64AnInteger(n) {
		return fmt.Sprintf("%d", int64(n))
	}

	return fmt.Sprintf("%g", n)
}
1059053
func ExtractAllowTyposOnNumericTokens(opts ...interface{}) *opt.AllowTyposOnNumericTokensOption {
	for _, o := range opts {
		if v, ok := o.(*opt.AllowTyposOnNumericTokensOption); ok {
			return v
		}
	}
	return nil
}
879412
func TrimToNumber(text string) string {
	leftTrimmed := strings.TrimLeftFunc(text, func(r rune) bool {
		return (r < '0' || r > '9') && r != '-'
	})

	return strings.TrimRightFunc(leftTrimmed, func(r rune) bool {
		return r < '0' || r > '9'
	})
}
1074039
func (api *Client) GetNumberInfo(number string) (*NumberInfo, error) {
	result, _, err := api.makeRequest(http.MethodGet, fmt.Sprintf("%s/%s", numberInfoPath, url.QueryEscape(number)), &NumberInfo{})
	if err != nil {
		return nil, err
	}
	return result.(*NumberInfo), nil
}
514803
func newIntegralNumeric(v Value) (numeric, error) {
	str := v.ToString()
	switch {
	case v.IsSigned():
		ival, err := strconv.ParseInt(str, 10, 64)
		if err != nil {
			return numeric{}, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", err)
		}
		return numeric{ival: ival, typ: Int64}, nil
	case v.IsUnsigned():
		uval, err := strconv.ParseUint(str, 10, 64)
		if err != nil {
			return numeric{}, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", err)
		}
		return numeric{uval: uval, typ: Uint64}, nil
	}

	// For other types, do best effort.
	if ival, err := strconv.ParseInt(str, 10, 64); err == nil {
		return numeric{ival: ival, typ: Int64}, nil
	}
	if uval, err := strconv.ParseUint(str, 10, 64); err == nil {
		return numeric{uval: uval, typ: Uint64}, nil
	}
	return numeric{}, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "could not parse value: '%s'", str)
}
1225370
func (t *translator) R(key interface{}, num1 float64, digits1 uint64, num2 float64, digits2 uint64, param1, param2 string) (string, error) {

	tarr, ok := t.rangeTanslations[key]
	if !ok {
		return unknownTranslation, ErrUnknowTranslation
	}

	rule := t.RangePluralRule(num1, digits1, num2, digits2)

	trans := tarr[rule]

	b := make([]byte, 0, 64)
	b = append(b, trans.text[:trans.indexes[0]]...)
	b = append(b, param1...)
	b = append(b, trans.text[trans.indexes[1]:trans.indexes[2]]...)
	b = append(b, param2...)
	b = append(b, trans.text[trans.indexes[3]:]...)

	return string(b), nil
}
29568
func maybeStripInternationalPrefixAndNormalize(
	number *builder.Builder,
	possibleIddPrefix string) PhoneNumber_CountryCodeSource {

	numBytes := number.Bytes()
	if len(numBytes) == 0 {
		return PhoneNumber_FROM_DEFAULT_COUNTRY
	}
	// Check to see if the number begins with one or more plus signs.
	ind := PLUS_CHARS_PATTERN.FindIndex(numBytes) // Return is an int pair [start,end]
	if len(ind) > 0 && ind[0] == 0 {              // Strictly match from string start
		number.ResetWith(numBytes[ind[1]:])
		// Can now normalize the rest of the number since we've consumed
		// the "+" sign at the start.
		number.ResetWithString(normalize(number.String()))
		return PhoneNumber_FROM_NUMBER_WITH_PLUS_SIGN
	}

	// Attempt to parse the first digits as an international prefix.
	iddPattern, ok := readFromRegexCache(possibleIddPrefix)
	if !ok {
		pat := possibleIddPrefix
		iddPattern = regexp.MustCompile(pat)
		writeToRegexCache(pat, iddPattern)
	}
	number.ResetWithString(normalize(string(numBytes)))
	if parsePrefixAsIdd(iddPattern, number) {
		return PhoneNumber_FROM_NUMBER_WITH_IDD
	}
	return PhoneNumber_FROM_DEFAULT_COUNTRY
}
762244
func parseNumber(tok *lexer.Token) (result float64, isInt bool) {
	var valInt int
	var err error

	valInt, err = strconv.Atoi(tok.Val)
	if err == nil {
		isInt = true

		result = float64(valInt)
	} else {
		isInt = false

		result, err = strconv.ParseFloat(tok.Val, 64)
		if err != nil {
			errToken(tok, fmt.Sprintf("Failed to parse number: %s", tok.Val))
		}
	}

	// named returned values
	return
}
410245
func (n Number) formatNumber(format *numberFormat, number float64) string {
	negative := number < 0

	// apply the multiplier first - this is mainly used for percents
	value := math.Abs(number * float64(format.multiplier))
	stringValue := ""

	// get the initial string value, with the maximum # decimal digits
	if format.maxDecimalDigits >= 0 {
		stringValue = numberRound(value, format.maxDecimalDigits)
	} else {
		stringValue = fmt.Sprintf("%f", value)
	}

	// separate the integer from the decimal parts
	pos := strings.Index(stringValue, ".")
	integer := stringValue
	decimal := ""
	if pos != -1 {
		integer = stringValue[:pos]
		decimal = stringValue[pos+1:]
	}

	// make sure the minimum # decimal digits are there
	for len(decimal) < format.minDecimalDigits {
		decimal = decimal + "0"
	}

	// make sure the minimum # integer digits are there
	for len(integer) < format.minIntegerDigits {
		integer = "0" + integer
	}

	// if there's a decimal portion, prepend the decimal point symbol
	if len(decimal) > 0 {
		decimal = string(n.Symbols.Decimal) + decimal
	}

	// put the integer portion into properly sized groups
	if format.groupSizeFinal > 0 && len(integer) > format.groupSizeFinal {
		if len(integer) > format.groupSizeMain {
			groupFinal := integer[len(integer)-format.groupSizeFinal:]
			groupFirst := integer[:len(integer)-format.groupSizeFinal]
			integer = strings.Join(
				chunkString(groupFirst, format.groupSizeMain),
				n.Symbols.Group,
			) + n.Symbols.Group + groupFinal
		}
	}

	// append/prepend negative/positive prefix/suffix
	formatted := ""
	if negative {
		formatted = format.negativePrefix + integer + decimal + format.negativeSuffix
	} else {
		formatted = format.positivePrefix + integer + decimal + format.positiveSuffix
	}

	// replace percents and permilles with the local symbols (likely to be exactly the same)
	formatted = strings.Replace(formatted, "%", string(n.Symbols.Percent), -1)
	formatted = strings.Replace(formatted, "‰", string(n.Symbols.PerMille), -1)

	return formatted
}
933274
func (p *DefaultWordTokenizer) IsNumber(t *Token) bool {
	return strings.HasPrefix(t.Tok, "##number##")
}
467474
func (v *Object) GetNumber(keys ...string) (json.Number, error) {
	child, err := v.getPath(keys)

	if err != nil {
		return "", err
	}
	n, err := child.Number()

	if err != nil {
		return "", err
	}
	return n, nil
}