| 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 |
| 5 | module context |
| 6 | |
| 7 | import 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. |
| 11 | pub struct ValueContext { |
| 12 | key Key |
| 13 | value Any |
| 14 | mut: |
| 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 |
| 28 | pub 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 | |
| 36 | // deadline returns the deadline from the parent context. |
| 37 | pub fn (ctx &ValueContext) deadline() ?time.Time { |
| 38 | return ctx.context.deadline() |
| 39 | } |
| 40 | |
| 41 | // done returns the done channel from the parent context. |
| 42 | pub fn (mut ctx ValueContext) done() chan int { |
| 43 | return ctx.context.done() |
| 44 | } |
| 45 | |
| 46 | // err returns the error from the parent context. |
| 47 | pub fn (mut ctx ValueContext) err() IError { |
| 48 | return ctx.context.err() |
| 49 | } |
| 50 | |
| 51 | // value returns the value associated with this context for the given key. |
| 52 | // If the key matches the one stored in this ValueContext, its value is returned. |
| 53 | // Otherwise, the lookup is delegated to the parent context. |
| 54 | pub fn (ctx &ValueContext) value(key Key) ?Any { |
| 55 | if ctx.key == key { |
| 56 | return ctx.value |
| 57 | } |
| 58 | return ctx.context.value(key) |
| 59 | } |
| 60 | |
| 61 | // str returns a string representation of the ValueContext, |
| 62 | // showing the parent context name suffixed with '.with_value'. |
| 63 | pub fn (ctx &ValueContext) str() string { |
| 64 | return context_name(ctx.context) + '.with_value' |
| 65 | } |
| 66 | |