Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RegExp: ignore case flag #39

Closed
wants to merge 1 commit into from
Closed

RegExp: ignore case flag #39

wants to merge 1 commit into from

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.

None yet

2 participants