intstr: add FromInt32, deprecate FromInt

This makes the source type explicit (without renaming the whole type),
and allows simpler construction.

Signed-off-by: Stephen Kitt <skitt@redhat.com>
This commit is contained in:
Stephen Kitt 2023-03-14 09:24:10 +01:00
parent 3125009dd1
commit 78e6cb1ccc
No known key found for this signature in database
GPG Key ID: 1CC5FA453662A71D
2 changed files with 18 additions and 6 deletions

View File

@ -54,7 +54,7 @@ const (
// FromInt creates an IntOrString object with an int32 value. It is
// your responsibility not to call this method with a value greater
// than int32.
// TODO: convert to (val int32)
// Deprecated: use FromInt32 instead.
func FromInt(val int) IntOrString {
if val > math.MaxInt32 || val < math.MinInt32 {
klog.Errorf("value: %d overflows int32\n%s\n", val, debug.Stack())
@ -62,6 +62,11 @@ func FromInt(val int) IntOrString {
return IntOrString{Type: Int, IntVal: int32(val)}
}
// FromInt32 creates an IntOrString object with an int32 value.
func FromInt32(val int32) IntOrString {
return IntOrString{Type: Int, IntVal: val}
}
// FromString creates an IntOrString object with a string value.
func FromString(val string) IntOrString {
return IntOrString{Type: String, StrVal: val}

View File

@ -31,6 +31,13 @@ func TestFromInt(t *testing.T) {
}
}
func TestFromInt32(t *testing.T) {
i := FromInt32(93)
if i.Type != Int || i.IntVal != 93 {
t.Errorf("Expected IntVal=93, got %+v", i)
}
}
func TestFromString(t *testing.T) {
i := FromString("76")
if i.Type != String || i.StrVal != "76" {
@ -47,7 +54,7 @@ func TestIntOrStringUnmarshalJSON(t *testing.T) {
input string
result IntOrString
}{
{"{\"val\": 123}", FromInt(123)},
{"{\"val\": 123}", FromInt32(123)},
{"{\"val\": \"123\"}", FromString("123")},
}
@ -67,7 +74,7 @@ func TestIntOrStringMarshalJSON(t *testing.T) {
input IntOrString
result string
}{
{FromInt(123), "{\"val\":123}"},
{FromInt32(123), "{\"val\":123}"},
{FromString("123"), "{\"val\":\"123\"}"},
}
@ -87,7 +94,7 @@ func TestIntOrStringMarshalJSONUnmarshalYAML(t *testing.T) {
cases := []struct {
input IntOrString
}{
{FromInt(123)},
{FromInt32(123)},
{FromString("123")},
}
@ -118,7 +125,7 @@ func TestGetIntFromIntOrString(t *testing.T) {
expectPerc bool
}{
{
input: FromInt(200),
input: FromInt32(200),
expectErr: false,
expectVal: 200,
expectPerc: false,
@ -191,7 +198,7 @@ func TestGetIntFromIntOrPercent(t *testing.T) {
expectVal int
}{
{
input: FromInt(123),
input: FromInt32(123),
expectErr: false,
expectVal: 123,
},