Skip to content

Commit

Permalink
src,doc: add documentation for per-binding state pattern
Browse files Browse the repository at this point in the history
PR-URL: #32538
Reviewed-By: James M Snell <jasnell@gmail.com>
  • Loading branch information
addaleax authored and BethGriggs committed Apr 7, 2020
1 parent 78c82a3 commit acac5df
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions src/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down

0 comments on commit acac5df

Please sign in to comment.