@@ -121,18 +121,34 @@ struct Callback {
121121class NativeString {
122122 char *data;
123123 size_t length;
124- char utf8ValueMemory[sizeof (String::Utf8Value)];
125- String::Utf8Value *utf8Value = nullptr ;
124+ bool strAllocated = false ;
126125 bool invalid = false ;
127126public:
128127 NativeString (Isolate *isolate, const Local<Value> &value) {
129128 if (value->IsUndefined ()) {
130129 data = nullptr ;
131130 length = 0 ;
132131 } else if (value->IsString ()) {
133- utf8Value = new (utf8ValueMemory) String::Utf8Value (isolate, value);
134- data = (**utf8Value);
135- length = utf8Value->length ();
132+ Local<String> string = Local<String>::Cast (value);
133+ #if NODE_MODULE_VERSION >= 137 // Node.js >= 24
134+ if (string->IsOneByte ()) {
135+ // utf8: direct access using ValueView
136+ String::ValueView strView (isolate, string);
137+ length = strView.length ();
138+ data = (char *) strView.data8 ();
139+ } else {
140+ // utf16: copy and convert to utf8
141+ strAllocated = true ;
142+ length = string->Utf8LengthV2 (isolate);
143+ data = new char [length];
144+ string->WriteUtf8V2 (isolate, data, length);
145+ }
146+ #else // Fallback Node.js < 24
147+ strAllocated = true ;
148+ length = string->Utf8Length (isolate);
149+ data = new char [length];
150+ string->WriteUtf8 (isolate, data, length, nullptr , String::WriteOptions::NO_NULL_TERMINATION );
151+ #endif
136152 } else if (value->IsArrayBufferView ()) { /* DataView or TypedArray */
137153 Local<ArrayBufferView> arrayBufferView = Local<ArrayBufferView>::Cast (value);
138154 auto contents = arrayBufferView->Buffer ()->GetBackingStore ();
@@ -165,8 +181,8 @@ class NativeString {
165181 }
166182
167183 ~NativeString () {
168- if (utf8Value ) {
169- utf8Value-> ~Utf8Value () ;
184+ if (strAllocated ) {
185+ delete[] data ;
170186 }
171187 }
172188};
0 commit comments