v / vlib / context / empty.v
80 lines · 67 sloc · 2.51 KB · 56e02481a4f0e421009413f58493620cc3a51f87
Raw
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// An EmptyContext is never canceled, has no values.
10// The done_ch field is an open channel that is never closed, returned by done()
11// on every call. This mirrors Go's context.Background().Done() == nil behavior:
12// selecting on this channel blocks forever, meaning the context is never done.
13pub struct EmptyContext {
14mut:
15 done_ch chan int
16}
17
18// deadline returns none, since an EmptyContext has no deadline.
19pub fn (ctx &EmptyContext) deadline() ?time.Time {
20 return none
21}
22
23// done returns an open channel that is never closed, since an EmptyContext can
24// never be canceled. Selecting on the returned channel blocks forever.
25// The same channel instance is returned on every call for a given EmptyContext.
26pub fn (mut ctx EmptyContext) done() chan int {
27 return ctx.done_ch
28}
29
30// err returns none, since an EmptyContext is never canceled.
31pub fn (ctx &EmptyContext) err() IError {
32 return none
33}
34
35// value returns none, since an EmptyContext carries no values.
36pub fn (ctx &EmptyContext) value(key Key) ?Any {
37 return none
38}
39
40// str returns a string describing the Context.
41pub fn (ctx &EmptyContext) str() string {
42 return 'unknown empty Context'
43}
44
45// A BackgroundContext is never canceled, has no values.
46struct BackgroundContext {
47 EmptyContext
48}
49
50// str returns a string describing the Context.
51pub fn (ctx &BackgroundContext) str() string {
52 return 'context.Background'
53}
54
55// background returns an empty Context. It is never canceled, has no
56// values, and has no deadline. It is typically used by the main function,
57// initialization, and tests, and as the top-level Context for incoming
58// requests.
59pub fn background() Context {
60 return &BackgroundContext{}
61}
62
63// A TodoContext is never canceled, has no values, and has no deadline. It is
64// never used for real work.
65struct TodoContext {
66 EmptyContext
67}
68
69// str returns a string describing the Context.
70pub fn (ctx &TodoContext) str() string {
71 return 'context.TODO'
72}
73
74// TODO: returns an empty Context. Code should use todo when
75// it's unclear which Context to use or it is not yet available (because the
76// surrounding function has not yet been extended to accept a Context
77// parameter).
78pub fn todo() Context {
79 return &TodoContext{}
80}
81