forked from Matir/adifparser
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
adifrecord.go
112 lines (100 loc) · 2.42 KB
/
adifrecord.go
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
package adifparser
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"strings"
)
// Public interface for ADIFRecords
type ADIFRecord interface {
// Print as ADIF String
ToString() string
// Fingerprint for duplication detection
Fingerprint() string
// Setters and getters
GetValue(string) (string, error)
SetValue(string, string)
// Get all of the present field names
GetFields() []string
// Delete a field
DeleteField(string) (bool, error)
}
// Internal implementation for ADIFRecord
type baseADIFRecord struct {
values map[string]string
}
// Errors
var ErrNoSuchField = errors.New("no such field")
// Create a new ADIFRecord from scratch
func NewADIFRecord() *baseADIFRecord {
record := &baseADIFRecord{}
record.values = make(map[string]string)
return record
}
func serializeField(name string, value string) string {
return fmt.Sprintf("<%s:%d>%s", name, len(value), value)
}
// Print an ADIFRecord as a string
func (r *baseADIFRecord) ToString() string {
var record bytes.Buffer
for _, n := range ADIFfieldOrder {
if v, ok := r.values[n]; ok {
record.WriteString(serializeField(n, v))
}
}
// Handle custom fields
for n, v := range r.values {
if !isStandardADIFField(n) {
record.WriteString(serializeField(n, v))
}
}
return record.String()
}
// Get fingerprint of ADIFRecord
func (r *baseADIFRecord) Fingerprint() string {
fpfields := []string{
"call", "station_callsign", "band",
"freq", "mode", "qso_date", "time_on",
"time_off"}
fpvals := make([]string, 0, len(fpfields))
for _, f := range fpfields {
if n, ok := r.values[f]; ok {
fpvals = append(fpvals, n)
}
}
fptext := strings.Join(fpvals, "|")
h := sha256.New()
h.Write([]byte(fptext))
return hex.EncodeToString(h.Sum(nil))
}
// Get a value
func (r *baseADIFRecord) GetValue(name string) (string, error) {
if v, ok := r.values[name]; ok {
return v, nil
}
return "", ErrNoSuchField
}
// Set a value
func (r *baseADIFRecord) SetValue(name string, value string) {
r.values[strings.ToLower(name)] = value
}
// Get all of the present field names
func (r *baseADIFRecord) GetFields() []string {
keys := make([]string, len(r.values))
i := 0
for k := range r.values {
keys[i] = k
i++
}
return keys
}
// Delete a field (from the internal map)
func (r *baseADIFRecord) DeleteField(name string) (bool, error) {
if _, ok := r.values[name]; ok {
delete(r.values, name)
return true, nil
}
return false, ErrNoSuchField
}