You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

int.go 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package types
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. // An IntMode is a mode for parsing integer values, representing a set of
  7. // accepted bases.
  8. type IntMode uint8
  9. // IntMode values for ParseInt; can be combined using binary or.
  10. const (
  11. Dec IntMode = 1 << iota
  12. Hex
  13. Oct
  14. )
  15. // String returns a string representation of IntMode; e.g. `IntMode(Dec|Hex)`.
  16. func (m IntMode) String() string {
  17. var modes []string
  18. if m&Dec != 0 {
  19. modes = append(modes, "Dec")
  20. }
  21. if m&Hex != 0 {
  22. modes = append(modes, "Hex")
  23. }
  24. if m&Oct != 0 {
  25. modes = append(modes, "Oct")
  26. }
  27. return "IntMode(" + strings.Join(modes, "|") + ")"
  28. }
  29. var errIntAmbig = fmt.Errorf("ambiguous integer value; must include '0' prefix")
  30. func prefix0(val string) bool {
  31. return strings.HasPrefix(val, "0") || strings.HasPrefix(val, "-0")
  32. }
  33. func prefix0x(val string) bool {
  34. return strings.HasPrefix(val, "0x") || strings.HasPrefix(val, "-0x")
  35. }
  36. // ParseInt parses val using mode into intptr, which must be a pointer to an
  37. // integer kind type. Non-decimal value require prefix `0` or `0x` in the cases
  38. // when mode permits ambiguity of base; otherwise the prefix can be omitted.
  39. func ParseInt(intptr interface{}, val string, mode IntMode) error {
  40. val = strings.TrimSpace(val)
  41. verb := byte(0)
  42. switch mode {
  43. case Dec:
  44. verb = 'd'
  45. case Dec + Hex:
  46. if prefix0x(val) {
  47. verb = 'v'
  48. } else {
  49. verb = 'd'
  50. }
  51. case Dec + Oct:
  52. if prefix0(val) && !prefix0x(val) {
  53. verb = 'v'
  54. } else {
  55. verb = 'd'
  56. }
  57. case Dec + Hex + Oct:
  58. verb = 'v'
  59. case Hex:
  60. if prefix0x(val) {
  61. verb = 'v'
  62. } else {
  63. verb = 'x'
  64. }
  65. case Oct:
  66. verb = 'o'
  67. case Hex + Oct:
  68. if prefix0(val) {
  69. verb = 'v'
  70. } else {
  71. return errIntAmbig
  72. }
  73. }
  74. if verb == 0 {
  75. panic("unsupported mode")
  76. }
  77. return ScanFully(intptr, val, verb)
  78. }