diff options
author | Anna Henningsen <anna@addaleax.net> | 2020-03-29 01:59:50 +0300 |
---|---|---|
committer | Anna Henningsen <anna@addaleax.net> | 2020-04-06 03:06:45 +0300 |
commit | 6d6de56571290412e052420f6425e0adb2eed1b2 (patch) | |
tree | 4ef9d5c12bd5de638ca55bc9d8b64833c253bf97 /src/README.md | |
parent | f4c2dff4e61570e6b8512f2a41ac2d17c2473a5e (diff) |
src,doc: add documentation for per-binding state pattern
PR-URL: https://github.com/nodejs/node/pull/32538
Reviewed-By: James M Snell <jasnell@gmail.com>
Diffstat (limited to 'src/README.md')
-rw-r--r-- | src/README.md | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/src/README.md b/src/README.md index 2e59c51c3c3..e2b256fba20 100644 --- a/src/README.md +++ b/src/README.md @@ -395,6 +395,50 @@ void Initialize(Local<Object> target, NODE_MODULE_CONTEXT_AWARE_INTERNAL(cares_wrap, Initialize) ``` +<a id="per-binding-state"> +#### Per-binding state + +Some internal bindings, such as the HTTP parser, maintain internal state that +only affects that particular binding. In that case, one common way to store +that state is through the use of `Environment::BindingScope`, which gives all +new functions created within it access to an object for storing such state. +That object is always a [`BaseObject`][]. + +```c++ +// In the HTTP parser source code file: +class BindingData : public BaseObject { + public: + BindingData(Environment* env, Local<Object> obj) : BaseObject(env, obj) {} + + std::vector<char> parser_buffer; + bool parser_buffer_in_use = false; + + // ... +}; + +// Available for binding functions, e.g. the HTTP Parser constructor: +static void New(const FunctionCallbackInfo<Value>& args) { + BindingData* binding_data = Unwrap<BindingData>(args.Data()); + new Parser(binding_data, args.This()); +} + +// ... because the initialization function told the Environment to use this +// BindingData class for all functions created by it: +void InitializeHttpParser(Local<Object> target, + Local<Value> unused, + Local<Context> context, + void* priv) { + Environment* env = Environment::GetCurrent(context); + Environment::BindingScope<BindingData> binding_scope(env); + if (!binding_scope) return; + BindingData* binding_data = binding_scope.data; + + // Created within the Environment::BindingScope + Local<FunctionTemplate> t = env->NewFunctionTemplate(Parser::New); + ... +} +``` + <a id="exception-handling"></a> ### Exception handling |