summaryrefslogtreecommitdiff
path: root/internal/rpn/variables.go
blob: eab654654bc35b735c3aef97f4bf33263321f2eb (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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 Paul Buetow

package rpn

import (
	"cmp"
	"encoding/json"
	"fmt"
	"os"
	"slices"
	"strings"
	"sync"
)

// Error variables for external error checking.
var (
	ErrVariableNotFound    = fmt.Errorf("variable not found")
	ErrInvalidVariableName = fmt.Errorf("invalid variable name")
)

// VariableInfo represents a single variable with its name and value.
type VariableInfo struct {
	Name  string
	Value float64
}

// Variables stores variable name-value pairs for RPN calculations.
// It provides thread-safe access to variable storage.
type Variables struct {
	mu        sync.RWMutex
	variables map[string]float64
}

// VariableReader defines the interface for reading variable storage.
type VariableReader interface {
	GetVariable(name string) (float64, bool)
	ListVariables() []VariableInfo
	FormatVariables() string
	Count() int
	HasVariable(name string) bool
}

// VariableWriter defines the interface for writing to variable storage.
type VariableWriter interface {
	SetVariable(name string, value float64) error
	DeleteVariable(name string) bool
	ClearVariables()
}

// VariablePersistence defines the interface for persisting variable storage to disk.
type VariablePersistence interface {
	// Save writes the variable store to a file in JSON format.
	Save(path string) error
	// Load reads the variable store from a file in JSON format.
	// All existing variables are replaced with the loaded values.
	Load(path string) error
}

// VariableStore combines VariableReader, VariableWriter, and VariablePersistence
// for full variable storage access.
type VariableStore interface {
	VariableReader
	VariableWriter
	VariablePersistence
}

// Ensure Variables implements all variable interfaces at compile time.
var (
	_ VariableReader      = (*Variables)(nil)
	_ VariableWriter      = (*Variables)(nil)
	_ VariablePersistence = (*Variables)(nil)
	_ VariableStore       = (*Variables)(nil)
)

// NewVariables creates and initializes a new Variables instance.
func NewVariables() *Variables {
	return &Variables{
		variables: make(map[string]float64),
	}
}

// isValidVariableName checks if a variable name is valid.
// Variable names must be non-empty and contain only alphanumeric characters and underscores.
//
// name: the variable name to validate
// Returns true if the name is valid, false otherwise
func isValidVariableName(name string) bool {
	if name == "" {
		return false
	}
	for _, r := range name {
		// Check if character is NOT alphanumeric or underscore
		// Apply De Morgan's law: !(P || Q || R || S) == !P && !Q && !R && !S
		// where P = 'a' <= r && r <= 'z' (lowercase)
		// Q = 'A' <= r && r <= 'Z' (uppercase)
		// R = '0' <= r && r <= '9' (digit)
		// S = r == '_' (underscore)
		// !P = r < 'a' || r > 'z'
		// !Q = r < 'A' || r > 'Z'
		// !R = r < '0' || r > '9'
		// !S = r != '_'
		if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') && (r < '0' || r > '9') && r != '_' {
			return false
		}
	}
	return true
}

// SetVariable assigns a value to a variable name.
// Usage: `name value =` stores value in variable.
func (v *Variables) SetVariable(name string, value float64) error {
	if !isValidVariableName(name) {
		return ErrInvalidVariableName
	}

	v.mu.Lock()
	defer v.mu.Unlock()

	v.variables[name] = value
	return nil
}

// GetVariable retrieves the value of a variable.
// Returns the value and true if found, or 0 and false if not found.
func (v *Variables) GetVariable(name string) (float64, bool) {
	v.mu.RLock()
	defer v.mu.RUnlock()

	value, exists := v.variables[name]
	return value, exists
}

// DeleteVariable removes a variable from storage.
// Usage: `name d` removes the variable.
func (v *Variables) DeleteVariable(name string) bool {
	v.mu.Lock()
	defer v.mu.Unlock()

	_, exists := v.variables[name]
	if exists {
		delete(v.variables, name)
	}
	return exists
}

// ListVariables returns a sorted list of all variable names and their values.
func (v *Variables) ListVariables() []VariableInfo {
	v.mu.RLock()
	defer v.mu.RUnlock()

	var infos []VariableInfo
	for name, value := range v.variables {
		infos = append(infos, VariableInfo{Name: name, Value: value})
	}

	sortVariableInfos(infos)

	return infos
}

// ClearVariables removes all variables from storage.
// Usage: `clear` removes all variables.
func (v *Variables) ClearVariables() {
	v.mu.Lock()
	defer v.mu.Unlock()

	clear(v.variables)
}

// formatVariablesUnsafe returns a list of variable info without acquiring a lock.
// The caller must hold a read lock.
func (v *Variables) formatVariablesUnsafe() string {
	var infos []VariableInfo
	for name, value := range v.variables {
		infos = append(infos, VariableInfo{Name: name, Value: value})
	}

	sortVariableInfos(infos)

	if len(infos) == 0 {
		return "No variables defined"
	}

	var sb strings.Builder
	for i, info := range infos {
		if i > 0 {
			sb.WriteString("\n")
		}
		// Use NumericValue interface for consistent formatting
		num := NewNumber(info.Value, FloatMode)
		sb.WriteString(info.Name)
		sb.WriteString(" = ")
		sb.WriteString(num.String())
	}
	return sb.String()
}

// FormatVariables formats all variables for display.
func (v *Variables) FormatVariables() string {
	v.mu.RLock()
	defer v.mu.RUnlock()

	return v.formatVariablesUnsafe()
}

// Count returns the number of defined variables.
func (v *Variables) Count() int {
	v.mu.RLock()
	defer v.mu.RUnlock()

	return len(v.variables)
}

// HasVariable checks if a variable exists.
func (v *Variables) HasVariable(name string) bool {
	v.mu.RLock()
	defer v.mu.RUnlock()

	_, exists := v.variables[name]
	return exists
}

// Save writes the variable store to a file in JSON format.
// The file path should be an absolute path.
// This method acquires a read lock and does not block concurrent readers.
func (v *Variables) Save(path string) error {
	v.mu.RLock()
	defer v.mu.RUnlock()

	// Convert variables to JSON-compatible format
	var infos []VariableInfo
	for name, value := range v.variables {
		infos = append(infos, VariableInfo{Name: name, Value: value})
	}

	sortVariableInfos(infos)

	return saveVariables(path, infos)
}

// Load reads the variable store from a file in JSON format.
// All existing variables are replaced with the loaded values.
// This method is thread-safe.
func (v *Variables) Load(path string) error {
	infos, err := loadVariables(path)
	if err != nil {
		return err
	}

	v.mu.Lock()
	defer v.mu.Unlock()

	// Clear existing variables and load from file
	v.variables = make(map[string]float64)
	for _, info := range infos {
		if isValidVariableName(info.Name) {
			v.variables[info.Name] = info.Value
		}
	}

	return nil
}

// sortVariableInfos sorts a slice of VariableInfo by name.
func sortVariableInfos(infos []VariableInfo) {
	slices.SortFunc(infos, func(a, b VariableInfo) int {
		return cmp.Compare(a.Name, b.Name)
	})
}

// saveVariables saves variable info to a file in JSON format.
// This is a helper function that does not acquire locks.
func saveVariables(path string, infos []VariableInfo) error {
	data, err := json.MarshalIndent(infos, "", "  ")
	if err != nil {
		return fmt.Errorf("failed to marshal variables: %w", err)
	}

	return os.WriteFile(path, data, 0644)
}

// loadVariables loads variable info from a file in JSON format.
// Returns an empty slice if the file doesn't exist.
// This is a helper function that does not acquire locks.
func loadVariables(path string) ([]VariableInfo, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		if os.IsNotExist(err) {
			return []VariableInfo{}, nil
		}
		return nil, fmt.Errorf("failed to read file: %w", err)
	}

	var infos []VariableInfo
	if err := json.Unmarshal(data, &infos); err != nil {
		return nil, fmt.Errorf("failed to unmarshal variables: %w", err)
	}

	return infos, nil
}