parse.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // parse.go
  2. package parse
  3. import (
  4. "fmt"
  5. "strings"
  6. "strconv"
  7. )
  8. // A ParseError indicates an error in converting a word into an integer.
  9. type ParseError struct {
  10. Index int // The index into the space-separated list of words.
  11. Word string // The word that generated the parse error.
  12. Err error // The raw error that precipitated this error, if any.
  13. }
  14. // String returns a human-readable error message.
  15. func (e *ParseError) String() string {
  16. return fmt.Sprintf("pkg parse: error parsing %q as int", e.Word)
  17. }
  18. // Parse parses the space-separated words in in put as integers.
  19. func Parse(input string) (numbers []int, err error) {
  20. defer func() {
  21. if r := recover(); r != nil {
  22. var ok bool
  23. err, ok = r.(error)
  24. if !ok {
  25. err = fmt.Errorf("pkg: %v", r)
  26. }
  27. }
  28. }()
  29. fields := strings.Fields(input)
  30. numbers = fields2numbers(fields)
  31. return
  32. }
  33. func fields2numbers(fields []string) (numbers []int) {
  34. if len(fields) == 0 {
  35. panic("no words to parse")
  36. }
  37. for idx, field := range fields {
  38. num, err := strconv.Atoi(field)
  39. if err != nil {
  40. panic(&ParseError{idx, field, err})
  41. }
  42. numbers = append(numbers, num)
  43. }
  44. return
  45. }