package langext

import (
	"fmt"
	"time"
)

func Coalesce[T any](v *T, def T) T {
	if v == nil {
		return def
	} else {
		return *v
	}
}

func CoalesceString(s *string, def string) string {
	if s == nil {
		return def
	} else {
		return *s
	}
}

func CoalesceInt(i *int, def int) int {
	if i == nil {
		return def
	} else {
		return *i
	}
}

func CoalesceInt32(i *int32, def int32) int32 {
	if i == nil {
		return def
	} else {
		return *i
	}
}

func CoalesceBool(b *bool, def bool) bool {
	if b == nil {
		return def
	} else {
		return *b
	}
}

func CoalesceTime(t *time.Time, def time.Time) time.Time {
	if t == nil {
		return def
	} else {
		return *t
	}
}

func CoalesceStringer(s fmt.Stringer, def string) string {
	if IsNil(s) {
		return def
	} else {
		return s.String()
	}
}

func SafeCast[T any](v any, def T) T {
	switch r := v.(type) {
	case T:
		return r
	default:
		return def
	}
}
