| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | package runtimecomp |
| 4 | |
| 5 | import "context" |
| 6 | |
| 7 | type contextKey struct{} |
| 8 | |
| 9 | // ContextWithService attaches a runtime component service to a context. |
| 10 | func ContextWithService(ctx context.Context, svc Service) context.Context { |
| 11 | if ctx == nil { |
| 12 | ctx = context.Background() |
| 13 | } |
| 14 | if svc == nil { |
| 15 | return ctx |
| 16 | } |
| 17 | return context.WithValue(ctx, contextKey{}, svc) |
| 18 | } |
| 19 | |
| 20 | // ServiceFromContext returns a runtime component service from a context. |
| 21 | func ServiceFromContext(ctx context.Context) (Service, bool) { |
| 22 | if ctx == nil { |
| 23 | return nil, false |
| 24 | } |
| 25 | svc, ok := ctx.Value(contextKey{}).(Service) |
| 26 | return svc, ok && svc != nil |
| 27 | } |