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

parse: add integral-slice type parsing support #84

Merged
merged 1 commit into from
Jan 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions parse/integral_slice.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package parse

import (
"fmt"
"strconv"
"strings"
"unsafe"
)

// SignedIntegralSlice splits on commas and parses into a slice of integers
// Parses with strconv.ParseInt and the base set to 0 so base prefixes are available.
// Whitespace is trimmed around the integers before parsing to allow for reasonable separtion (shell word-splitting aside)
func SignedIntegralSlice[I int | int64 | int32 | int16 | int8](s string) ([]I, error) {
parts := strings.Split(s, ",")
out := make([]I, len(parts))

bitSize := int(unsafe.Sizeof(I(0)) * 8)

for i, p := range parts {
val, parseErr := strconv.ParseInt(strings.TrimSpace(p), 0, bitSize)
if parseErr != nil {
return nil, fmt.Errorf("failed to parse integer index %d: %w", i, parseErr)
}
out[i] = I(val)
}
return out, nil
}

// UnsignedIntegralSlice splits on commas and parses into a slice of integers
// Parses with strconv.ParseInt and the base set to 0 so base prefixes are available.
// Whitespace is trimmed around the integers before parsing to allow for reasonable separtion (shell word-splitting aside)
func UnsignedIntegralSlice[I uint | uint64 | uint32 | uint16 | uint8 | uintptr](s string) ([]I, error) {
parts := strings.Split(s, ",")
out := make([]I, len(parts))

bitSize := int(unsafe.Sizeof(I(0)) * 8)

for i, p := range parts {
val, parseErr := strconv.ParseUint(strings.TrimSpace(p), 0, bitSize)
if parseErr != nil {
return nil, fmt.Errorf("failed to parse integer index %d: %w", i, parseErr)
}
out[i] = I(val)
}
return out, nil
}
Loading
Loading