func ParseToByteQuantity()

in pkg/bytequantity/bytequantity.go [42:101]


func ParseToByteQuantity(byteQuantityStr string) (ByteQuantity, error) {
	bqRegexp := regexp.MustCompile(byteQuantityRegex)
	matches := bqRegexp.FindStringSubmatch(strings.ToLower(byteQuantityStr))
	if len(matches) < 2 {
		return ByteQuantity{}, fmt.Errorf("%s is not a valid byte quantity", byteQuantityStr)
	}

	quantityStr := matches[1]
	unit := gib
	if len(matches) > 2 && matches[2] != "" {
		unit = matches[2]
	}
	quantity := uint64(0)
	switch strings.ToLower(string(unit[0])) {
	// mib
	case "m":
		inputDecSplit := strings.Split(quantityStr, ".")
		if len(inputDecSplit) == 2 {
			d, err := strconv.Atoi(inputDecSplit[1])
			if err != nil {
				return ByteQuantity{}, err
			}
			if d != 0 {
				return ByteQuantity{}, fmt.Errorf("cannot accept floating point MB value, only integers are accepted")
			}
		}
		// need error here so that this quantity doesn't bind in the local scope
		var err error
		quantity, err = strconv.ParseUint(inputDecSplit[0], 10, 64)
		if err != nil {
			return ByteQuantity{}, err
		}
	// gib
	case "g":
		quantityDec, err := strconv.ParseFloat(quantityStr, 64)
		if err != nil {
			return ByteQuantity{}, err
		}
		if quantityDec > maxGiB {
			return ByteQuantity{}, fmt.Errorf("error GiB value is too large")
		}
		quantity = uint64(quantityDec * gbConvert)
	// tib
	case "t":
		quantityDec, err := strconv.ParseFloat(quantityStr, 64)
		if err != nil {
			return ByteQuantity{}, err
		}
		if quantityDec > maxTiB {
			return ByteQuantity{}, fmt.Errorf("error TiB value is too large")
		}
		quantity = uint64(quantityDec * tbConvert)
	default:
		return ByteQuantity{}, fmt.Errorf("error unit %s is not supported", unit)
	}

	return ByteQuantity{
		Quantity: quantity,
	}, nil
}