Skip to content

RegExp: ignore case flag#39

Closed
vanodevium wants to merge 1 commit intodocker:masterfrom
vanodevium:master
Closed

RegExp: ignore case flag#39
vanodevium wants to merge 1 commit intodocker:masterfrom
vanodevium:master

Conversation

@vanodevium
Copy link

No description provided.

@kolyshkin
Copy link
Contributor

We are getting rid of using regexp in this library; it is faster and smaller that way; see #40

@vanodevium
Copy link
Author

vanodevium commented Apr 28, 2022

@kolyshkin No problem. Good choice!

Maybe next code would be useful...

var units = []byte("kmgtpezy")

func parseString(sizeStr string) (int64, error) {
	sizeStr = strings.ToLower(sizeStr)
	strLen := len(sizeStr)
	if strLen == 0 {
		return -1, fmt.Errorf("invalid size: '%s'", sizeStr)
	}
	var unitPrefixPos, lastNumberPos int
	var binary bool
	for i := strLen - 1; i >= 0; i-- {
		if unicode.IsDigit(rune(sizeStr[i])) {
			lastNumberPos = i
			break
		}

		if sizeStr[i] == 'i' {
			binary = true
			continue
		}

		if sizeStr[i] != ' ' {
			unitPrefixPos = i
		}
	}

	size, err := strconv.ParseFloat(sizeStr[:lastNumberPos+1], 64)
	if err != nil {
		return -1, err
	}

	if size < 0 {
		return -1, fmt.Errorf("size is less than zero")
	}

	if unitPrefixPos > 0 {
		index := bytes.IndexByte(units, sizeStr[unitPrefixPos])
		if index != -1 {
			base := 1000
			if binary {
				base = 1024
			}
			size *= math.Pow(float64(base), float64(index+1))
		}
	}

	return int64(size), nil
}

This code can parse human readable string, but looks only for valid suffix.
The main goal is that it not used map with unit and multiplier, only simple math :)

@vanodevium vanodevium closed this Apr 28, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants