123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051includeAmbient_context_coreletdefault_storage=Default_.storageopenstruct(** The current ambient-context storage. *)letcur_storage:Storage.tAtomic.t=Atomic.makeDefault_.storageendlet[@inline]get_current_storage()=Atomic.getcur_storage(* NOTE: we can't really "map" each local context from the old to the new. Maybe the old
storage is TLS based and the new one is per-lwt-task. *)letset_current_storage(storage:Storage.t)=Atomic.setcur_storagestorage(** {2 Functions operating with the current storage} *)(** Get the context from the current storage, or [Hmap.empty] if there is no
ambient context. *)let[@inline]get_context()=Storage.get_context(Atomic.getcur_storage)(** [with_context ctx f] calls [f()] in an ambient context in which
[get_context()] will return [ctx]. Once [f()] returns, the storage is reset
to its previous value. *)let[@inline]with_contextctxf=Storage.with_context(Atomic.getcur_storage)ctxf(** Get the ambient context and then look up [k] in it *)let[@inline]get(k:'aContext.key):'aoption=Hmap.findk(get_context())(** Create a new key *)letnew_key:unit->'aContext.key=Hmap.Key.create(** [with_key_bound_to storage k v f] calls [f()] in a context updated to have
[k] map to [v]. *)letwith_key_bound_tokvf=letstorage=get_current_storage()inletctx=Storage.get_contextstorageinletnew_ctx=Hmap.addkvctxinStorage.with_contextstoragenew_ctxf(** [with_key_unbound k f] calls [f()] in a context updated to have [k] bound to
no value. *)letwith_key_unboundkf=letstorage=Atomic.getcur_storageinletctx=Storage.get_contextstorageinifHmap.memkctxthen(letnew_ctx=Hmap.remkctxinStorage.with_contextstoragenew_ctxf)elsef()