diff --git a/option.go b/option.go index 32b43023..0e2165dc 100644 --- a/option.go +++ b/option.go @@ -13,6 +13,8 @@ const ( Bool = reflect.Bool Int = reflect.Int Uint = reflect.Uint + Int64 = reflect.Int64 + Uint64 = reflect.Uint64 Float = reflect.Float64 String = reflect.String ) @@ -95,6 +97,20 @@ var converters = map[reflect.Kind]converter{ } return uint(val), err }, + Int64: func(v string) (interface{}, error) { + val, err := strconv.ParseInt(v, 0, 64) + if err != nil { + return nil, err + } + return val, err + }, + Uint64: func(v string) (interface{}, error) { + val, err := strconv.ParseUint(v, 0, 64) + if err != nil { + return nil, err + } + return val, err + }, Float: func(v string) (interface{}, error) { return strconv.ParseFloat(v, 64) }, @@ -152,6 +168,12 @@ func IntOption(names ...string) Option { func UintOption(names ...string) Option { return NewOption(Uint, names...) } +func Int64Option(names ...string) Option { + return NewOption(Int64, names...) +} +func Uint64Option(names ...string) Option { + return NewOption(Uint64, names...) +} func FloatOption(names ...string) Option { return NewOption(Float, names...) } @@ -209,6 +231,28 @@ func (ov *OptionValue) Uint() (value uint, found bool, err error) { return val, ov.ValueFound, err } +func (ov *OptionValue) Int64() (value int64, found bool, err error) { + if ov == nil || !ov.ValueFound && ov.Value == nil { + return 0, false, nil + } + val, ok := ov.Value.(int64) + if !ok { + err = fmt.Errorf("expected type %T, got %T", val, ov.Value) + } + return val, ov.ValueFound, err +} + +func (ov *OptionValue) Uint64() (value uint64, found bool, err error) { + if ov == nil || !ov.ValueFound && ov.Value == nil { + return 0, false, nil + } + val, ok := ov.Value.(uint64) + if !ok { + err = fmt.Errorf("expected type %T, got %T", val, ov.Value) + } + return val, ov.ValueFound, err +} + func (ov *OptionValue) Float() (value float64, found bool, err error) { if ov == nil || !ov.ValueFound && ov.Value == nil { return 0, false, nil diff --git a/option_test.go b/option_test.go index 29458347..ed7729c0 100644 --- a/option_test.go +++ b/option_test.go @@ -1,6 +1,7 @@ package cmdkit import ( + "math" "reflect" "strings" "testing" @@ -77,6 +78,11 @@ func TestParse(t *testing.T) { {opt: IntOption("int2"), str: "-42", v: -42}, {opt: UintOption("uint1"), str: "23", v: uint(23)}, {opt: UintOption("uint2"), str: "-23", err: `strconv.ParseUint: parsing "-23": invalid syntax`}, + {opt: Int64Option("int3"), str: "100001", v: int64(100001)}, + {opt: Int64Option("int3"), str: "2147483648", v: int64(math.MaxInt32 + 1)}, + {opt: Int64Option("int3"), str: "fly", err: `strconv.ParseInt: parsing "fly": invalid syntax`}, + {opt: Uint64Option("uint3"), str: "23", v: uint64(23)}, + {opt: Uint64Option("uint3"), str: "-23", err: `strconv.ParseUint: parsing "-23": invalid syntax`}, {opt: BoolOption("true"), str: "true", v: true}, {opt: BoolOption("true"), str: "", v: true}, {opt: BoolOption("false"), str: "false", v: false},