diff options
| author | Stefan Majewsky <majewsky@gmx.net> | 2025-07-01 15:09:23 +0200 |
|---|---|---|
| committer | Stefan Majewsky <majewsky@gmx.net> | 2025-07-01 15:09:34 +0200 |
| commit | e95f01274201b6fde1c1ea7818c7a7e0a77f0f43 (patch) | |
| tree | 291c24fb67db5e3db254c4baf43e3d95e50c069b | |
| parent | a6dd82541baf2699ae53d6e7582bf0b9e2186bbd (diff) | |
| download | go-gg-e95f01274201b6fde1c1ea7818c7a7e0a77f0f43.tar.gz | |
refined: initial sketch for type Struct
| -rw-r--r-- | refined/struct.go | 12 | ||||
| -rw-r--r-- | refined/struct_test.go | 54 |
2 files changed, 66 insertions, 0 deletions
diff --git a/refined/struct.go b/refined/struct.go new file mode 100644 index 0000000..35a0c85 --- /dev/null +++ b/refined/struct.go @@ -0,0 +1,12 @@ +// SPDX-FileCopyrightText: 2025 Stefan Majewsky <majewsky@gmx.net> +// SPDX-License-Identifier: Apache-2.0 + +package refined + +type Struct[P any] struct { + Has P +} + +func NewStruct[P any](payload P) Struct[P] { + return Struct[P]{Has: payload} +} diff --git a/refined/struct_test.go b/refined/struct_test.go new file mode 100644 index 0000000..b07b8a5 --- /dev/null +++ b/refined/struct_test.go @@ -0,0 +1,54 @@ +// SPDX-FileCopyrightText: 2025 Stefan Majewsky <majewsky@gmx.net> +// SPDX-License-Identifier: Apache-2.0 + +package refined_test + +import ( + "fmt" + "math" + "regexp" + "testing" + + . "github.com/majewsky/gg/internal/test" + "github.com/majewsky/gg/refined" +) + +type AccountID struct { + refined.Scalar[AccountID, uint64] +} + +func (AccountID) Refine(c refined.Challenge[AccountID, uint64]) (AccountID, error) { + s, err := refined.RangeCheck(c, 1, math.MaxUint64) + return AccountID{s}, err +} + +type AccountName struct { + refined.Scalar[AccountName, string] +} + +var accountNameRx = regexp.MustCompile(`^[a-z][a-z0-9_]*$`) + +func (AccountName) Refine(c refined.Challenge[AccountName, string]) (AccountName, error) { + s, err := refined.RegexpCheck(c, accountNameRx) + return AccountName{s}, err +} + +type AccountInfo = refined.Struct[AccountInfoPayload] + +type AccountInfoPayload struct { + ID AccountID `json:"id,omitzero"` + Name AccountName `json:"name,omitzero"` +} + +func (p AccountInfoPayload) ReadableName() string { + return fmt.Sprintf("%s (ID %d)", p.Name.Raw(), p.ID.Raw()) +} + +func TestAccountInfo(t *testing.T) { + var info AccountInfo //nolint:staticcheck + info = refined.NewStruct(AccountInfoPayload{ + ID: refined.Literal[AccountID](53), + }) + info.Has.Name = refined.Literal[AccountName]("hello") + AssertEqual(t, info.Has.ReadableName(), "hello (ID 53)") +} |
