1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
|
package prototool
import (
"reflect"
"time"
"google.golang.org/protobuf/types/known/durationpb"
)
// NotNil ensures that the memory that the field pointer is pointing to is not nil.
// field must be a valid pointer. It's target is checked for nil-ness and populated if it's nil.
func NotNil(field interface{}) {
v := reflect.ValueOf(field)
vValue := v.Elem() // follow the pointer
if !vValue.IsNil() {
return
}
vValue.Set(reflect.New(vValue.Type().Elem()))
}
func Duration(d **durationpb.Duration, defaultValue time.Duration) {
if *d == nil {
*d = durationpb.New(defaultValue)
}
}
func String(s *string, defaultValue string) {
if *s == "" {
*s = defaultValue
}
}
func StringPtr(s **string, defaultValue string) {
if *s == nil {
*s = &defaultValue
}
}
func Float64(s *float64, defaultValue float64) {
if *s == 0 {
*s = defaultValue
}
}
func Int32Ptr(d **int32, defaultValue int32) {
if *d == nil {
*d = &defaultValue
}
}
func Uint32(d *uint32, defaultValue uint32) {
if *d == 0 {
*d = defaultValue
}
}
func Uint32Ptr(d **uint32, defaultValue uint32) {
if *d == nil {
*d = &defaultValue
}
}
|