aboutsummaryrefslogtreecommitdiff
path: root/refined/value.go
blob: a15e4f10dcad40bc497703a66d70003626b254dc (plain)
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// SPDX-FileCopyrightText: 2025 Stefan Majewsky <majewsky@gmx.net>
// SPDX-License-Identifier: Apache-2.0

package refined

import (
	"encoding/json"
	"errors"

	. "github.com/majewsky/gg/option"
)

type Scalar[S any, V any] struct {
	value Option[V]
}

func (s Scalar[S, V]) Raw() V {
	return s.value.UnwrapOrPanic("TODO 1")
}

func New[S IsAScalar[S, V], V any](value V) (S, error) {
	var empty S
	if empty.RefinedMatch(value) {
		return empty.RefinedBuild(PreScalar[S, V]{value: Some(value)}), nil
	} else {
		return empty, errors.New("TODO 2")
	}
}

func Literal[S IsAScalar[S, V], V any](value V) S {
	s, err := New[S, V](value)
	if err != nil {
		panic(err.Error())
	}
	return s
}

func (s Scalar[S, V]) MarshalJSON() ([]byte, error) {
	return json.Marshal(s.Raw())
}

func (s *Scalar[S, V]) UnmarshalJSON(buf []byte) error {
	var value V
	err := json.Unmarshal(buf, &value)
	if err != nil {
		return err
	}

	// We cannot directly call `New[S, V](value)` here because we cannot prove statically
	// that `S` satisfies `IsAScalar[S, V]`.
	var empty S
	if r, ok := any(empty).(IsAScalar[S, V]); ok {
		if r.RefinedMatch(value) {
			*s = Scalar[S, V]{value: Some(value)}
			return nil
		} else {
			return errors.New("TODO 3")
		}
	} else {
		return errors.New("TODO 4")
	}
}

type IsAScalar[S any, V any] interface {
	// We need both steps separately. New() wants to have an S at the end, which goes through both steps.
	// But Unmarshal...() wants to obtain a Scalar[S, V], so it only wants to use the first step.
	RefinedMatch(V) bool
	RefinedBuild(PreScalar[S, V]) S
}

type PreScalar[S any, V any] struct {
	value Option[V]
}

func (p PreScalar[S, V]) Into() Scalar[S, V] {
	if p.value.IsNone() {
		panic("broken PreScalar object")
	}
	return Scalar[S, V](p)
}