From 6d6de56571290412e052420f6425e0adb2eed1b2 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Sat, 28 Mar 2020 23:59:50 +0100 Subject: [PATCH] src,doc: add documentation for per-binding state pattern PR-URL: https://github.com/nodejs/node/pull/32538 Reviewed-By: James M Snell --- src/README.md | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/src/README.md b/src/README.md index 2e59c51c3c37e9..e2b256fba20de8 100644 --- a/src/README.md +++ b/src/README.md @@ -395,6 +395,50 @@ void Initialize(Local target, NODE_MODULE_CONTEXT_AWARE_INTERNAL(cares_wrap, Initialize) ``` + +#### 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 obj) : BaseObject(env, obj) {} + + std::vector parser_buffer; + bool parser_buffer_in_use = false; + + // ... +}; + +// Available for binding functions, e.g. the HTTP Parser constructor: +static void New(const FunctionCallbackInfo& args) { + BindingData* binding_data = Unwrap(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 target, + Local unused, + Local context, + void* priv) { + Environment* env = Environment::GetCurrent(context); + Environment::BindingScope binding_scope(env); + if (!binding_scope) return; + BindingData* binding_data = binding_scope.data; + + // Created within the Environment::BindingScope + Local t = env->NewFunctionTemplate(Parser::New); + ... +} +``` + ### Exception handling