| 1 | from rpython.rtyper.lltypesystem import rffi |
| 2 | from pypy.interpreter.error import OperationError |
| 3 | from pypy.module._hpy_universal.apiset import API |
| 4 | from pypy.module._hpy_universal import llapi |
| 5 | |
| 6 | @API.func("HPy HPyContextVar_New(HPyContext *ctx, const char *name, HPy default_value)") |
| 7 | def HPyContextVar_New(space, handles, ctx, name, h_default): |
| 8 | if name: |
| 9 | w_str = space.newbytes(rffi.constcharp2str(name)) |
| 10 | w_name = space.call_method(w_str, 'decode', space.newtext("utf-8")) |
| 11 | else: |
| 12 | w_name = space.newtext('') |
| 13 | if h_default: |
| 14 | w_def = handles.deref(h_default) |
| 15 | w_ret = space.appexec([w_name, w_def], """(name, default): |
| 16 | from _contextvars import ContextVar |
| 17 | return ContextVar(name, default=default) |
| 18 | """) |
| 19 | else: |
| 20 | w_ret = space.appexec([w_name], """(name,): |
| 21 | from _contextvars import ContextVar |
| 22 | return ContextVar(name) |
| 23 | """) |
| 24 | return handles.new(w_ret) |
| 25 | |
| 26 | @API.func("HPy HPyContextVar_Set(HPyContext *ctx, HPy context_var, HPy value)") |
| 27 | def HPyContextVar_Set(space, handles, ctx, h_ovar, h_val): |
| 28 | w_ovar = handles.deref(h_ovar) |
| 29 | w_val = handles.deref(h_val) |
| 30 | w_ret = space.appexec([w_ovar, w_val], """(ovar, val): |
| 31 | from _contextvars import ContextVar |
| 32 | if not isinstance(ovar, ContextVar): |
| 33 | raise TypeError('an instance of ContextVar was expected') |
| 34 | return ovar.set(val) |
| 35 | """) |
| 36 | return handles.new(w_ret) |
| 37 | |
| 38 | @API.func("int HPyContextVar_Get(HPyContext *ctx, HPy context_var, HPy default_value, HPy *result)", error_value=API.int(-1)) |
| 39 | def HPyContextVar_Get(space, handles, ctx, h_ovar, h_default, val): |
| 40 | w_ovar = handles.deref(h_ovar) |
| 41 | if h_default: |
| 42 | w_def = handles.deref(h_default) |
| 43 | w_ret = space.appexec([w_ovar, w_def], """(ovar, default): |
| 44 | from _contextvars import ContextVar |
| 45 | if not isinstance(ovar, ContextVar): |
| 46 | raise TypeError('an instance of ContextVar was expected') |
| 47 | return ovar.get(default) |
| 48 | """) |
| 49 | else: |
| 50 | try: |
| 51 | w_ret = space.appexec([w_ovar], """(ovar,): |
| 52 | from _contextvars import ContextVar |
| 53 | if not isinstance(ovar, ContextVar): |
| 54 | raise TypeError('an instance of ContextVar was expected') |
| 55 | return ovar.get() |
| 56 | """) |
| 57 | except OperationError as e: |
| 58 | if e.match(space, space.w_LookupError): |
| 59 | val[0] = llapi.cts.cast("HPy", 0) |
| 60 | return API.int(0) |
| 61 | raise e |
| 62 | h = handles.new(w_ret) |
| 63 | val[0] = h |
| 64 | return API.int(0) |