Debian Codegraph @

flag_int.go

raw symbols SCIP
1 package cli
2
3 import (
4 "strconv"
5 "unsafe"
6 )
7
8 type (
9 IntFlag = FlagBase[int, IntegerConfig, intValue[int]]
10 Int8Flag = FlagBase[int8, IntegerConfig, intValue[int8]]
11 Int16Flag = FlagBase[int16, IntegerConfig, intValue[int16]]
12 Int32Flag = FlagBase[int32, IntegerConfig, intValue[int32]]
13 Int64Flag = FlagBase[int64, IntegerConfig, intValue[int64]]
14 )
15
16 // IntegerConfig is the configuration for all integer type flags
17 type IntegerConfig struct {
18 Base int
19 }
20
21 // -- int Value
22 type intValue[T int | int8 | int16 | int32 | int64] struct {
23 val *T
24 base int
25 }
26
27 // Below functions are to satisfy the ValueCreator interface
28
29 func (i intValue[T]) Create(val T, p *T, c IntegerConfig) Value {
30 *p = val
31
32 return &intValue[T]{
33 val: p,
34 base: c.Base,
35 }
36 }
37
38 func (i intValue[T]) ToString(b T) string {
39 i.val = &b
40 return i.String()
41 }
42
43 // Below functions are to satisfy the flag.Value interface
44
45 func (i *intValue[T]) Set(s string) error {
46 v, err := strconv.ParseInt(s, i.base, int(unsafe.Sizeof(T(0))*8))
47 if err != nil {
48 return err
49 }
50 *i.val = T(v)
51 return err
52 }
53
54 func (i *intValue[T]) Get() any { return *i.val }
55
56 func (i *intValue[T]) String() string {
57 base := i.base
58 if base == 0 {
59 base = 10
60 }
61
62 return strconv.FormatInt(int64(*i.val), base)
63 }
64
65 // Int looks up the value of a local Int64Flag, returns
66 // 0 if not found
67 func (cmd *Command) Int(name string) int {
68 return getInt[int](cmd, name)
69 }
70
71 // Int8 looks up the value of a local Int8Flag, returns
72 // 0 if not found
73 func (cmd *Command) Int8(name string) int8 {
74 return getInt[int8](cmd, name)
75 }
76
77 // Int16 looks up the value of a local Int16Flag, returns
78 // 0 if not found
79 func (cmd *Command) Int16(name string) int16 {
80 return getInt[int16](cmd, name)
81 }
82
83 // Int32 looks up the value of a local Int32Flag, returns
84 // 0 if not found
85 func (cmd *Command) Int32(name string) int32 {
86 return getInt[int32](cmd, name)
87 }
88
89 // Int64 looks up the value of a local Int64Flag, returns
90 // 0 if not found
91 func (cmd *Command) Int64(name string) int64 {
92 return getInt[int64](cmd, name)
93 }
94
95 func getInt[T int | int8 | int16 | int32 | int64](cmd *Command, name string) T {
96 if v, ok := cmd.Value(name).(T); ok {
97 tracef("int available for flag name %[1]q with value=%[2]v (cmd=%[3]q)", name, v, cmd.Name)
98
99 return v
100 }
101
102 tracef("int NOT available for flag name %[1]q (cmd=%[2]q)", name, cmd.Name)
103 return 0
104 }