github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/x/contextx/value.go (about) 1 package contextx 2 3 import ( 4 "context" 5 "reflect" 6 ) 7 8 // WithValue like context.WithValue but faster 9 func WithValue(parent context.Context, k, v interface{}) context.Context { 10 if parent == nil { 11 panic("parent is nil") 12 } 13 if k == nil { 14 panic("key is nil") 15 } 16 return &kvc{parent, k, v} 17 } 18 19 type kvc struct { 20 context.Context 21 k, v interface{} 22 } 23 24 func (c *kvc) String() string { 25 return nameof(c.Context) + 26 ".WithValue(type " + reflect.TypeOf(c.k).String() + 27 ", val" + stringify(c.v) + ")" 28 } 29 30 func (c *kvc) Value(k interface{}) interface{} { 31 if c.k == k { 32 return c.v 33 } 34 return c.Context.Value(k) 35 } 36 37 type stringer interface{ String() string } 38 39 func nameof(c context.Context) string { 40 if str, ok := c.(stringer); ok { 41 return str.String() 42 } 43 return reflect.TypeOf(c).String() 44 } 45 46 func stringify(v interface{}) string { 47 switch s := v.(type) { 48 case stringer: 49 return s.String() 50 case string: 51 return s 52 } 53 return "<not Stringer>" 54 }