1+ #include " env-inl.h"
2+ #include " node.h"
3+ #include " node_external_reference.h"
4+ #include " node_internals.h"
5+ #include " util-inl.h"
6+ #include " v8-fast-api-calls.h"
7+ #include " v8.h"
8+
9+ namespace node {
10+
11+ using v8::ArrayBuffer;
12+ using v8::BackingStore;
13+ using v8::CFunction;
14+ using v8::Context;
15+ using v8::FastApiTypedArray;
16+ using v8::FastOneByteString;
17+ using v8::Isolate;
18+ using v8::Local;
19+ using v8::Object;
20+ using v8::String;
21+ using v8::Uint8Array;
22+ using v8::Value;
23+
24+ namespace encoding_methods {
25+
26+ void EncodeUtf8 (const v8::FunctionCallbackInfo<Value>& args) {
27+ Environment* env = Environment::GetCurrent (args);
28+ Isolate* isolate = env->isolate ();
29+ CHECK_GE (args.Length (), 2 );
30+ CHECK (args[0 ]->IsString ());
31+ CHECK (args[1 ]->IsUint8Array ());
32+
33+ Local<String> str = args[0 ].As <String>();
34+ Local<Uint8Array> out = args[1 ].As <Uint8Array>();
35+ Local<ArrayBuffer> buf = out->Buffer ();
36+ size_t out_length = out->ByteLength ();
37+ char * write_result = static_cast <char *>(buf->Data ()) + out->ByteOffset ();
38+
39+ str->WriteUtf8 (isolate,
40+ write_result,
41+ out_length,
42+ nullptr ,
43+ String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8);
44+ }
45+
46+ void latin1_to_utf8 (const char * str, char * c) {
47+ for (; *str; ++str) {
48+ if (*str & 0x80 ) {
49+ *c++ = *str;
50+ } else {
51+ *c++ = (char )(0xc0 | (unsigned )*str >> 6 );
52+ *c++ = (char )(0x80 | (*str & 0x3f ));
53+ }
54+ }
55+ *c++ = ' \0 ' ;
56+ }
57+
58+ void FastEncodeUtf8 (Local<Value> receiver,
59+ const FastOneByteString& source,
60+ const FastApiTypedArray<uint8_t >& output) {
61+ uint8_t * storage;
62+ auto is_available = output.getStorageIfAligned (&storage);
63+ CHECK (is_available);
64+ latin1_to_utf8 (source.data , reinterpret_cast <char *>(storage));
65+ }
66+
67+ CFunction fast_encode_utf8_ (CFunction::Make(FastEncodeUtf8));
68+
69+ static void Initialize (Local<Object> target,
70+ Local<Value> unused,
71+ Local<Context> context,
72+ void * priv) {
73+ SetFastMethod (context, target, " encodeUtf8" , EncodeUtf8, &fast_encode_utf8_);
74+ }
75+
76+ void RegisterExternalReferences (ExternalReferenceRegistry* registry) {
77+ registry->Register (EncodeUtf8);
78+ registry->Register (FastEncodeUtf8);
79+ registry->Register (fast_encode_utf8_.GetTypeInfo ());
80+ }
81+
82+ } // namespace encoding_methods
83+ } // namespace node
84+
85+ NODE_BINDING_CONTEXT_AWARE_INTERNAL (encoding_methods,
86+ node::encoding_methods::Initialize)
87+ NODE_BINDING_EXTERNAL_REFERENCE(
88+ encoding_methods, node::encoding_methods::RegisterExternalReferences)
0 commit comments