feat(pkg): add initial source code

This commit is contained in:
Piotr Icikowski 2023-07-21 23:05:40 +02:00
parent d708f36317
commit 124070116f
Signed by: Piotr Icikowski
GPG Key ID: 3931CA47A91F7666
5 changed files with 111 additions and 0 deletions

11
go.mod Normal file
View File

@ -0,0 +1,11 @@
module pkg.icikowski.pl/generics
go 1.20
require github.com/stretchr/testify v1.8.4
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

10
go.sum Normal file
View File

@ -0,0 +1,10 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

4
package.go Normal file
View File

@ -0,0 +1,4 @@
/*
Generics-related functions
*/
package generics

23
ptr.go Normal file
View File

@ -0,0 +1,23 @@
package generics
// Ptr returns pointer for given value
func Ptr[T any](val T) *T {
return &val
}
// Val returns value of given pointer or default value if pointer is nil
func Val[T any](ptr *T) T {
var val T
if ptr != nil {
val = *ptr
}
return val
}
// Fallback returns value of given pointer or fallback value if pointer is nil
func Fallback[T any](ptr *T, fallback T) T {
if ptr != nil {
return *ptr
}
return fallback
}

63
ptr_test.go Normal file
View File

@ -0,0 +1,63 @@
package generics
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestPtr(t *testing.T) {
num := new(int)
*num = 8
require.Equal(t, num, *Ptr(num))
}
func TestVal(t *testing.T) {
num := new(int)
*num = 8
tests := map[string]struct {
input *int
expectedResult int
}{
"non-nil pointer": {
input: num,
expectedResult: *num,
},
"nil pointer": {},
}
for name, tc := range tests {
name, tc := name, tc
t.Run(name, func(t *testing.T) {
require.Equal(t, tc.expectedResult, Val(tc.input))
})
}
}
func TestFallback(t *testing.T) {
num := new(int)
*num = 8
fallback := 9
tests := map[string]struct {
input *int
expectedResult int
}{
"non-nil pointer": {
input: num,
expectedResult: *num,
},
"nil pointer": {
expectedResult: fallback,
},
}
for name, tc := range tests {
name, tc := name, tc
t.Run(name, func(t *testing.T) {
require.Equal(t, tc.expectedResult, Fallback(tc.input, tc.expectedResult))
})
}
}