sourcegraph/lib/pointers/ptr.go
Robert Lin cb3a1e4dc8
feat/sg: add 'sg enterprise' commands for Cody Analytics (#63414)
Closes CORE-194 - added a bit more than strictly needed here, but this
PR adds:

- `sg enterprise subscription list`
- `sg enterprise subscription set-instance-domain`
- `sg enterprise update-membership`
- `sg enterprise license list`

## Test plan

<img width="1055" alt="image"
src="https://github.com/sourcegraph/sourcegraph/assets/23356519/48ec40b0-fbac-4513-9ad8-fc3174774ada">


![image](https://github.com/sourcegraph/sourcegraph/assets/23356519/806fd054-806b-4ecb-a969-32900112f368)
2024-06-21 16:29:31 -07:00

76 lines
1.6 KiB
Go

package pointers
import "fmt"
// Ptr returns a pointer to any value.
// Useful in tests or when pointer without a variable is needed.
func Ptr[T any](val T) *T {
return &val
}
// NonZeroPtr returns nil for zero value, otherwise pointer to value
func NonZeroPtr[T comparable](val T) *T {
var zero T
if val == zero {
return nil
}
return Ptr(val)
}
// Deref safely dereferences a pointer. If pointer is nil, returns default value,
// otherwise returns dereferenced value.
func Deref[T any](v *T, defaultValue T) T {
if v != nil {
return *v
}
return defaultValue
}
// Deref safely dereferences a pointer. If pointer is nil, it returns a zero value,
// otherwise returns dereferenced value.
func DerefZero[T any](v *T) T {
if v != nil {
return *v
}
var defaultValue T
return defaultValue
}
type numberType interface {
~float32 | ~float64 |
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}
// Float64 returns a pointer to the provided numeric value as a float64.
func Float64[T numberType](v T) *float64 {
return Ptr(float64(v))
}
// Stringf is an alias for Ptr(fmt.Sprintf(format, a...))
func Stringf(format string, a ...any) *string {
return Ptr(fmt.Sprintf(format, a...))
}
// Slice takes a slice of values and turns it into a slice of pointers.
func Slice[S []V, V any](s S) []*V {
slice := make([]*V, len(s))
for i, v := range s {
v := v // copy
slice[i] = &v
}
return slice
}
// NilIfZero returns nil if the provided value is zero, otherwise returns pointer
// to the value.
func NilIfZero[T comparable](val T) *T {
var zero T
if val == zero {
return nil
}
return &val
}