55 lines
1.1 KiB
Go
55 lines
1.1 KiB
Go
package queue
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
)
|
|
|
|
type Queue struct {
|
|
Elements []string
|
|
FilePath string
|
|
}
|
|
|
|
func NewQueue(filePath string) (*Queue, error) {
|
|
q := &Queue{
|
|
Elements: make([]string, 0),
|
|
FilePath: filePath,
|
|
}
|
|
|
|
// Load state from file
|
|
if _, err := os.Stat(filePath); err == nil {
|
|
data, err := os.ReadFile(filePath)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("error reading state file: %w", err)
|
|
}
|
|
if err := json.Unmarshal(data, &q.Elements); err != nil {
|
|
return nil, fmt.Errorf("error parsing state file: %w", err)
|
|
}
|
|
}
|
|
return q, nil
|
|
}
|
|
|
|
func (q *Queue) Enqueue(element string) {
|
|
q.Elements = append(q.Elements, element)
|
|
}
|
|
|
|
func (q *Queue) Dequeue() (string, error) {
|
|
if len(q.Elements) == 0 {
|
|
return "", fmt.Errorf("queue is empty")
|
|
}
|
|
element := q.Elements[0]
|
|
q.Elements = q.Elements[1:]
|
|
return element, nil
|
|
}
|
|
|
|
func (q *Queue) Save() error {
|
|
data, err := json.Marshal(q.Elements)
|
|
if err != nil {
|
|
return fmt.Errorf("error serializing state: %w", err)
|
|
}
|
|
if err := os.WriteFile(q.FilePath, data, 0644); err != nil {
|
|
return fmt.Errorf("error writing state to file: %w", err)
|
|
}
|
|
return nil
|
|
}
|