summaryrefslogtreecommitdiff
path: root/pkg/values.go
blob: d18b499ecca9a3a9df0cad62c1f4d73ae44d84c7 (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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package gonf

import (
	"fmt"
	"log/slog"
	"strconv"
	"strings"
)

type Value interface {
	Bytes() []byte
	Int() (int, error)
	String() string
}

func interfaceToValue(v any) Value {
	switch vv := v.(type) {
	case []byte:
		return &BytesValue{vv}
	case int:
		return &IntValue{vv}
	case string:
		return &StringValue{vv}
	case *VariablePromise:
		return vv
	default:
		slog.Error("interfaceToValue", "value", v, "error", "Not Implemented")
		panic(fmt.Sprintf("interfaceToValue cannot take type %T as argument. Value was %#v.", v, v))
	}
}

func interfaceToTemplateValue(v any) Value {
	if vv, ok := v.([]byte); ok {
		return &TemplateValue{data: string(vv)}
	}
	if vv, ok := v.(int); ok {
		return &IntValue{vv}
	}
	if vv, ok := v.(string); ok {
		return &TemplateValue{data: vv}
	}
	if vv, ok := v.(*VariablePromise); ok {
		return vv
	}
	slog.Error("interfaceToTemplateValue", "value", v, "error", "Not Implemented")
	panic(fmt.Sprintf("interfaceToTemplateValue cannot take type %T as argument. Value was %#v.", v, v))
}

type BytesValue struct {
	value []byte
}

func (b BytesValue) Bytes() []byte {
	return b.value
}
func (b BytesValue) Int() (int, error) {
	return strconv.Atoi(string(b.value))
}
func (b BytesValue) String() string {
	return string(b.value[:])
}

type IntValue struct {
	value int
}

func (i IntValue) Bytes() []byte {
	return []byte(strconv.Itoa(i.value))
}
func (i IntValue) Int() (int, error) {
	return i.value, nil
}
func (i IntValue) String() string {
	return strconv.Itoa(i.value)
}

type StringsListValue struct {
	value []string
}

func (s *StringsListValue) Append(v ...string) {
	s.value = append(s.value, v...)
}
func (s StringsListValue) Bytes() []byte {
	return []byte(s.String())
}
func (s StringsListValue) Int() (int, error) {
	return len(s.value), nil
}
func (s StringsListValue) String() string {
	return strings.Join(s.value, "\n")
}

type StringValue struct {
	value string
}

func (s StringValue) Bytes() []byte {
	return []byte(s.value)
}
func (s StringValue) Int() (int, error) {
	return strconv.Atoi(s.value)
}
func (s StringValue) String() string {
	return s.value
}

// TODO maps

// TODO what else?