v / vlib / context
Raw file | 57 loc (49 sloc) | 1.57 KB | Latest commit hash 0386f2bbe
1// This module defines the Context type, which carries deadlines, cancellation signals,
2// and other request-scoped values across API boundaries and between processes.
3// Based on: https://github.com/golang/go/tree/master/src/context
4// Last commit: https://github.com/golang/go/commit/52bf14e0e8bdcd73f1ddfb0c4a1d0200097d3ba2
5module context
6
7import time
8
9// A ValueContext carries a key-value pair. It implements Value for that key and
10// delegates all other calls to the embedded Context.
11pub struct ValueContext {
12 key Key
13 value Any
14mut:
15 context Context
16}
17
18// with_value returns a copy of parent in which the value associated with key is
19// val.
20//
21// Use context Values only for request-scoped data that transits processes and
22// APIs, not for passing optional parameters to functions.
23//
24// The provided key must be comparable and should not be of type
25// string or any other built-in type to avoid collisions between
26// packages using context. Users of with_value should define their own
27// types for keys
28pub fn with_value(parent Context, key Key, value Any) Context {
29 return &ValueContext{
30 context: parent
31 key: key
32 value: value
33 }
34}
35
36pub fn (ctx &ValueContext) deadline() ?time.Time {
37 return ctx.context.deadline()
38}
39
40pub fn (mut ctx ValueContext) done() chan int {
41 return ctx.context.done()
42}
43
44pub fn (mut ctx ValueContext) err() IError {
45 return ctx.context.err()
46}
47
48pub fn (ctx &ValueContext) value(key Key) ?Any {
49 if ctx.key == key {
50 return ctx.value
51 }
52 return ctx.context.value(key)
53}
54
55pub fn (ctx &ValueContext) str() string {
56 return context_name(ctx.context) + '.with_value'
57}