-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.go
More file actions
71 lines (63 loc) · 1.88 KB
/
context.go
File metadata and controls
71 lines (63 loc) · 1.88 KB
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
package context
import "github.com/tinywasm/fmt"
// Context is a minimalist context compatible with TinyGo.
// No maps, no channels, uses a fixed array of 16 key-value pairs.
type Context struct {
pairs [16]fmt.KeyValue
count uint8
}
// errCapacityExceeded is returned when the context reaches its maximum capacity of 16 pairs.
var errCapacityExceeded = fmt.Err("context: max 16 values exceeded")
// Background returns an empty Context (equivalent to context.Background).
func Background() *Context {
return &Context{}
}
// WithValue creates a new Context with the additional key-value pair.
// Returns errCapacityExceeded if the capacity of 16 pairs is exceeded.
func WithValue(parent *Context, key, value string) (*Context, error) {
ctx := &Context{}
if parent != nil {
ctx.pairs = parent.pairs
ctx.count = parent.count
}
if ctx.count >= 16 {
return nil, errCapacityExceeded
}
ctx.pairs[ctx.count] = fmt.KeyValue{Key: key, Value: value}
ctx.count++
return ctx, nil
}
// Set adds or updates a key-value pair in-place.
// Returns an error if the capacity of 16 pairs is exceeded.
func (c *Context) Set(key, value string) error {
if c.count >= 16 {
return errCapacityExceeded
}
c.pairs[c.count] = fmt.KeyValue{Key: key, Value: value}
c.count++
return nil
}
// Value searches for the value associated with key (reverse search to prioritize latest values).
func (c *Context) Value(key string) string {
if c == nil {
return ""
}
for i := int(c.count) - 1; i >= 0; i-- {
if c.pairs[i].Key == key {
return c.pairs[i].Value
}
}
return ""
}
// Keys returns a slice containing all keys in the context.
// Later values with duplicate keys are not deduplicated - all keys are returned.
func (c *Context) Keys() []string {
if c == nil || c.count == 0 {
return nil
}
keys := make([]string, c.count)
for i := uint8(0); i < c.count; i++ {
keys[i] = c.pairs[i].Key
}
return keys
}