gotosocial/vendor/codeberg.org/gruf/go-errors/data.go

108 lines
2.1 KiB
Go
Raw Normal View History

2021-11-13 11:29:08 +00:00
package errors
import (
"fmt"
2021-11-13 11:29:08 +00:00
"sync"
2022-01-16 17:52:30 +00:00
"codeberg.org/gruf/go-format"
2021-11-13 11:29:08 +00:00
)
2021-11-27 14:26:58 +00:00
// KV is a structure for setting key-value pairs in ErrorData.
2021-11-13 11:29:08 +00:00
type KV struct {
Key string
Value interface{}
}
// ErrorData defines a way to set and access contextual error data.
2021-11-27 14:26:58 +00:00
// The default implementation of this is thread-safe.
2021-11-13 11:29:08 +00:00
type ErrorData interface {
// Value will attempt to fetch value for given key in ErrorData
Value(string) (interface{}, bool)
// Append adds the supplied key-values to ErrorData, similar keys DO overwrite
Append(...KV)
// Implement byte slice representation formatter.
2022-01-16 17:52:30 +00:00
format.Formattable
// Implement string representation formatter.
fmt.Stringer
2021-11-13 11:29:08 +00:00
}
2021-11-27 14:26:58 +00:00
// NewData returns a new ErrorData implementation.
2021-11-13 11:29:08 +00:00
func NewData() ErrorData {
return &errorData{
data: make([]KV, 0, 10),
2021-11-13 11:29:08 +00:00
}
}
// errorData is our ErrorData implementation, this is essentially
2021-11-27 14:26:58 +00:00
// just a thread-safe string-interface map implementation.
2021-11-13 11:29:08 +00:00
type errorData struct {
data []KV
2021-11-13 11:29:08 +00:00
mu sync.Mutex
}
func (d *errorData) set(key string, value interface{}) {
for i := range d.data {
if d.data[i].Key == key {
// Found existing, update!
d.data[i].Value = value
return
}
}
// Add new KV entry to slice
d.data = append(d.data, KV{
Key: key,
Value: value,
})
}
2021-11-13 11:29:08 +00:00
func (d *errorData) Value(key string) (interface{}, bool) {
d.mu.Lock()
for i := range d.data {
if d.data[i].Key == key {
v := d.data[i].Value
d.mu.Unlock()
return v, true
}
}
2021-11-13 11:29:08 +00:00
d.mu.Unlock()
return nil, false
2021-11-13 11:29:08 +00:00
}
func (d *errorData) Append(kvs ...KV) {
d.mu.Lock()
for i := range kvs {
d.set(kvs[i].Key, kvs[i].Value)
2021-11-13 11:29:08 +00:00
}
d.mu.Unlock()
}
func (d *errorData) AppendFormat(b []byte) []byte {
2022-01-16 17:52:30 +00:00
buf := format.Buffer{B: b}
2021-11-13 11:29:08 +00:00
d.mu.Lock()
buf.B = append(buf.B, '{')
2022-01-16 17:52:30 +00:00
// Append data as kv pairs
for i := range d.data {
2022-01-16 17:52:30 +00:00
key := d.data[i].Key
val := d.data[i].Value
format.Appendf(&buf, "{:k}={:v} ", key, val)
}
2022-01-16 17:52:30 +00:00
// Drop trailing space
if len(d.data) > 0 {
buf.Truncate(1)
}
buf.B = append(buf.B, '}')
2021-11-13 11:29:08 +00:00
d.mu.Unlock()
return buf.B
}
func (d *errorData) String() string {
return string(d.AppendFormat(nil))
2021-11-13 11:29:08 +00:00
}