GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_buffer.cc Lines: 551 614 89.7 %
Date: 2020-02-19 22:14:06 Branches: 400 670 59.7 %

Line Branch Exec Source
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
#include "node_buffer.h"
23
#include "node.h"
24
#include "node_errors.h"
25
#include "node_internals.h"
26
27
#include "env-inl.h"
28
#include "string_bytes.h"
29
#include "string_search.h"
30
#include "util-inl.h"
31
#include "v8.h"
32
33
#include <cstring>
34
#include <climits>
35
36
#define THROW_AND_RETURN_UNLESS_BUFFER(env, obj)                            \
37
  THROW_AND_RETURN_IF_NOT_BUFFER(env, obj, "argument")                      \
38
39
#define THROW_AND_RETURN_IF_OOB(r)                                          \
40
  do {                                                                      \
41
    if ((r).IsNothing()) return;                                            \
42
    if (!(r).FromJust())                                                    \
43
      return node::THROW_ERR_OUT_OF_RANGE(env, "Index out of range");       \
44
  } while (0)                                                               \
45
46
namespace node {
47
namespace Buffer {
48
49
using v8::ArrayBuffer;
50
using v8::ArrayBufferView;
51
using v8::BackingStore;
52
using v8::Context;
53
using v8::EscapableHandleScope;
54
using v8::FunctionCallbackInfo;
55
using v8::Global;
56
using v8::HandleScope;
57
using v8::Int32;
58
using v8::Integer;
59
using v8::Isolate;
60
using v8::Just;
61
using v8::Local;
62
using v8::Maybe;
63
using v8::MaybeLocal;
64
using v8::Nothing;
65
using v8::Number;
66
using v8::Object;
67
using v8::String;
68
using v8::Uint32;
69
using v8::Uint32Array;
70
using v8::Uint8Array;
71
using v8::Value;
72
using v8::WeakCallbackInfo;
73
74
namespace {
75
76
class CallbackInfo {
77
 public:
78
  ~CallbackInfo();
79
80
  static inline void Free(char* data, void* hint);
81
  static inline CallbackInfo* New(Environment* env,
82
                                  Local<ArrayBuffer> object,
83
                                  FreeCallback callback,
84
                                  char* data,
85
                                  void* hint = nullptr);
86
87
  CallbackInfo(const CallbackInfo&) = delete;
88
  CallbackInfo& operator=(const CallbackInfo&) = delete;
89
90
 private:
91
  static void CleanupHook(void* data);
92
  static void WeakCallback(const WeakCallbackInfo<CallbackInfo>&);
93
  inline void WeakCallback(Isolate* isolate);
94
  inline CallbackInfo(Environment* env,
95
                      Local<ArrayBuffer> object,
96
                      FreeCallback callback,
97
                      char* data,
98
                      void* hint);
99
  Global<ArrayBuffer> persistent_;
100
  FreeCallback const callback_;
101
  char* const data_;
102
  void* const hint_;
103
  Environment* const env_;
104
};
105
106
107
void CallbackInfo::Free(char* data, void*) {
108
  ::free(data);
109
}
110
111
112
22
CallbackInfo* CallbackInfo::New(Environment* env,
113
                                Local<ArrayBuffer> object,
114
                                FreeCallback callback,
115
                                char* data,
116
                                void* hint) {
117
22
  return new CallbackInfo(env, object, callback, data, hint);
118
}
119
120
121
22
CallbackInfo::CallbackInfo(Environment* env,
122
                           Local<ArrayBuffer> object,
123
                           FreeCallback callback,
124
                           char* data,
125
22
                           void* hint)
126
    : persistent_(env->isolate(), object),
127
      callback_(callback),
128
      data_(data),
129
      hint_(hint),
130
44
      env_(env) {
131
44
  std::shared_ptr<BackingStore> obj_backing = object->GetBackingStore();
132
22
  CHECK_EQ(data_, static_cast<char*>(obj_backing->Data()));
133
22
  if (object->ByteLength() != 0)
134
20
    CHECK_NOT_NULL(data_);
135
136
22
  persistent_.SetWeak(this, WeakCallback, v8::WeakCallbackType::kParameter);
137
22
  env->AddCleanupHook(CleanupHook, this);
138
22
  env->isolate()->AdjustAmountOfExternalAllocatedMemory(sizeof(*this));
139
22
}
140
141
142
51
CallbackInfo::~CallbackInfo() {
143
17
  persistent_.Reset();
144
17
  env_->RemoveCleanupHook(CleanupHook, this);
145
17
}
146
147
148
5
void CallbackInfo::CleanupHook(void* data) {
149
5
  CallbackInfo* self = static_cast<CallbackInfo*>(data);
150
151
  {
152
10
    HandleScope handle_scope(self->env_->isolate());
153
10
    Local<ArrayBuffer> ab = self->persistent_.Get(self->env_->isolate());
154
5
    CHECK(!ab.IsEmpty());
155
5
    ab->Detach();
156
  }
157
158
5
  self->WeakCallback(self->env_->isolate());
159
5
}
160
161
162
17
void CallbackInfo::WeakCallback(
163
    const WeakCallbackInfo<CallbackInfo>& data) {
164
17
  CallbackInfo* self = data.GetParameter();
165
17
  self->WeakCallback(data.GetIsolate());
166
17
  delete self;
167
17
}
168
169
170
22
void CallbackInfo::WeakCallback(Isolate* isolate) {
171
22
  callback_(data_, hint_);
172
22
  int64_t change_in_bytes = -static_cast<int64_t>(sizeof(*this));
173
  isolate->AdjustAmountOfExternalAllocatedMemory(change_in_bytes);
174
22
}
175
176
177
// Parse index for external array data. An empty Maybe indicates
178
// a pending exception. `false` indicates that the index is out-of-bounds.
179
3316016
inline MUST_USE_RESULT Maybe<bool> ParseArrayIndex(Environment* env,
180
                                                   Local<Value> arg,
181
                                                   size_t def,
182
                                                   size_t* ret) {
183
6632032
  if (arg->IsUndefined()) {
184
    *ret = def;
185
    return Just(true);
186
  }
187
188
  int64_t tmp_i;
189
9948048
  if (!arg->IntegerValue(env->context()).To(&tmp_i))
190
    return Nothing<bool>();
191
192
3316016
  if (tmp_i < 0)
193
4
    return Just(false);
194
195
  // Check that the result fits in a size_t.
196
3316012
  const uint64_t kSizeMax = static_cast<uint64_t>(static_cast<size_t>(-1));
197
  // coverity[pointless_expression]
198
  if (static_cast<uint64_t>(tmp_i) > kSizeMax)
199
    return Just(false);
200
201
3316012
  *ret = static_cast<size_t>(tmp_i);
202
3316012
  return Just(true);
203
}
204
205
}  // anonymous namespace
206
207
// Buffer methods
208
209
4515344
bool HasInstance(Local<Value> val) {
210
4515344
  return val->IsArrayBufferView();
211
}
212
213
214
828983
bool HasInstance(Local<Object> obj) {
215
828983
  return obj->IsArrayBufferView();
216
}
217
218
219
238109
char* Data(Local<Value> val) {
220
238109
  CHECK(val->IsArrayBufferView());
221
238109
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
222
714327
  return static_cast<char*>(ui->Buffer()->GetBackingStore()->Data()) +
223
476218
      ui->ByteOffset();
224
}
225
226
227
111622
char* Data(Local<Object> obj) {
228
111622
  return Data(obj.As<Value>());
229
}
230
231
232
100592
size_t Length(Local<Value> val) {
233
100592
  CHECK(val->IsArrayBufferView());
234
100592
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
235
100592
  return ui->ByteLength();
236
}
237
238
239
108158
size_t Length(Local<Object> obj) {
240
108158
  CHECK(obj->IsArrayBufferView());
241
108158
  Local<ArrayBufferView> ui = obj.As<ArrayBufferView>();
242
108158
  return ui->ByteLength();
243
}
244
245
246
15813
MaybeLocal<Uint8Array> New(Environment* env,
247
                           Local<ArrayBuffer> ab,
248
                           size_t byte_offset,
249
                           size_t length) {
250
31626
  CHECK(!env->buffer_prototype_object().IsEmpty());
251
15813
  Local<Uint8Array> ui = Uint8Array::New(ab, byte_offset, length);
252
  Maybe<bool> mb =
253
47439
      ui->SetPrototype(env->context(), env->buffer_prototype_object());
254
15813
  if (mb.IsNothing())
255
    return MaybeLocal<Uint8Array>();
256
15813
  return ui;
257
}
258
259
MaybeLocal<Uint8Array> New(Isolate* isolate,
260
                           Local<ArrayBuffer> ab,
261
                           size_t byte_offset,
262
                           size_t length) {
263
  Environment* env = Environment::GetCurrent(isolate);
264
  if (env == nullptr) {
265
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
266
    return MaybeLocal<Uint8Array>();
267
  }
268
  return New(env, ab, byte_offset, length);
269
}
270
271
272
70
MaybeLocal<Object> New(Isolate* isolate,
273
                       Local<String> string,
274
                       enum encoding enc) {
275
70
  EscapableHandleScope scope(isolate);
276
277
  size_t length;
278
140
  if (!StringBytes::Size(isolate, string, enc).To(&length))
279
    return Local<Object>();
280
70
  size_t actual = 0;
281
70
  char* data = nullptr;
282
283
70
  if (length > 0) {
284
70
    data = UncheckedMalloc(length);
285
286
70
    if (data == nullptr) {
287
      THROW_ERR_MEMORY_ALLOCATION_FAILED(isolate);
288
      return Local<Object>();
289
    }
290
291
70
    actual = StringBytes::Write(isolate, data, length, string, enc);
292
70
    CHECK(actual <= length);
293
294
70
    if (actual == 0) {
295
1
      free(data);
296
1
      data = nullptr;
297
69
    } else if (actual < length) {
298
      data = node::Realloc(data, actual);
299
    }
300
  }
301
302
140
  return scope.EscapeMaybe(New(isolate, data, actual));
303
}
304
305
306
1
MaybeLocal<Object> New(Isolate* isolate, size_t length) {
307
1
  EscapableHandleScope handle_scope(isolate);
308
  Local<Object> obj;
309
1
  Environment* env = Environment::GetCurrent(isolate);
310
1
  if (env == nullptr) {
311
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
312
    return MaybeLocal<Object>();
313
  }
314
2
  if (Buffer::New(env, length).ToLocal(&obj))
315
1
    return handle_scope.Escape(obj);
316
  return Local<Object>();
317
}
318
319
320
3458
MaybeLocal<Object> New(Environment* env, size_t length) {
321
3458
  EscapableHandleScope scope(env->isolate());
322
323
  // V8 currently only allows a maximum Typed Array index of max Smi.
324
3458
  if (length > kMaxLength) {
325
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
326
    return Local<Object>();
327
  }
328
329
6916
  AllocatedBuffer ret(env);
330
3458
  if (length > 0) {
331
2955
    ret = env->AllocateManaged(length, false);
332
2955
    if (ret.data() == nullptr) {
333
      THROW_ERR_MEMORY_ALLOCATION_FAILED(env);
334
      return Local<Object>();
335
    }
336
  }
337
338
6916
  return scope.EscapeMaybe(ret.ToBuffer());
339
}
340
341
342
2041
MaybeLocal<Object> Copy(Isolate* isolate, const char* data, size_t length) {
343
2041
  EscapableHandleScope handle_scope(isolate);
344
2041
  Environment* env = Environment::GetCurrent(isolate);
345
2041
  if (env == nullptr) {
346
1
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
347
1
    return MaybeLocal<Object>();
348
  }
349
  Local<Object> obj;
350
4080
  if (Buffer::Copy(env, data, length).ToLocal(&obj))
351
2040
    return handle_scope.Escape(obj);
352
  return Local<Object>();
353
}
354
355
356
10547
MaybeLocal<Object> Copy(Environment* env, const char* data, size_t length) {
357
10547
  EscapableHandleScope scope(env->isolate());
358
359
  // V8 currently only allows a maximum Typed Array index of max Smi.
360
10547
  if (length > kMaxLength) {
361
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
362
    return Local<Object>();
363
  }
364
365
21094
  AllocatedBuffer ret(env);
366
10547
  if (length > 0) {
367
10409
    CHECK_NOT_NULL(data);
368
10409
    ret = env->AllocateManaged(length, false);
369
10409
    if (ret.data() == nullptr) {
370
      THROW_ERR_MEMORY_ALLOCATION_FAILED(env);
371
      return Local<Object>();
372
    }
373
10409
    memcpy(ret.data(), data, length);
374
  }
375
376
21094
  return scope.EscapeMaybe(ret.ToBuffer());
377
}
378
379
380
22
MaybeLocal<Object> New(Isolate* isolate,
381
                       char* data,
382
                       size_t length,
383
                       FreeCallback callback,
384
                       void* hint) {
385
22
  EscapableHandleScope handle_scope(isolate);
386
22
  Environment* env = Environment::GetCurrent(isolate);
387
22
  if (env == nullptr) {
388
    callback(data, hint);
389
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
390
    return MaybeLocal<Object>();
391
  }
392
  return handle_scope.EscapeMaybe(
393
44
      Buffer::New(env, data, length, callback, hint));
394
}
395
396
397
22
MaybeLocal<Object> New(Environment* env,
398
                       char* data,
399
                       size_t length,
400
                       FreeCallback callback,
401
                       void* hint) {
402
22
  EscapableHandleScope scope(env->isolate());
403
404
22
  if (length > kMaxLength) {
405
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
406
    callback(data, hint);
407
    return Local<Object>();
408
  }
409
410
411
  // The buffer will be released by a CallbackInfo::New() below,
412
  // hence this BackingStore callback is empty.
413
  std::unique_ptr<BackingStore> backing =
414
      ArrayBuffer::NewBackingStore(data,
415
                                   length,
416
64
                                   [](void*, size_t, void*){},
417
44
                                   nullptr);
418
  Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(),
419
22
                                           std::move(backing));
420
  // TODO(thangktran): drop this check when V8 is pumped to 8.0 .
421
22
  if (!ab->IsExternal())
422
44
    ab->Externalize(ab->GetBackingStore());
423
66
  if (ab->SetPrivate(env->context(),
424
                     env->arraybuffer_untransferable_private_symbol(),
425
66
                     True(env->isolate())).IsNothing()) {
426
    callback(data, hint);
427
    return Local<Object>();
428
  }
429
22
  MaybeLocal<Uint8Array> ui = Buffer::New(env, ab, 0, length);
430
431
22
  CallbackInfo::New(env, ab, callback, data, hint);
432
433
22
  if (ui.IsEmpty())
434
    return MaybeLocal<Object>();
435
436
22
  return scope.Escape(ui.ToLocalChecked());
437
}
438
439
// Warning: This function needs `data` to be allocated with malloc() and not
440
// necessarily isolate's ArrayBuffer::Allocator.
441
70
MaybeLocal<Object> New(Isolate* isolate, char* data, size_t length) {
442
70
  EscapableHandleScope handle_scope(isolate);
443
70
  Environment* env = Environment::GetCurrent(isolate);
444
70
  if (env == nullptr) {
445
    free(data);
446
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
447
    return MaybeLocal<Object>();
448
  }
449
  Local<Object> obj;
450
140
  if (Buffer::New(env, data, length, true).ToLocal(&obj))
451
70
    return handle_scope.Escape(obj);
452
  return Local<Object>();
453
}
454
455
// Warning: If this call comes through the public node_buffer.h API,
456
// the contract for this function is that `data` is allocated with malloc()
457
// and not necessarily isolate's ArrayBuffer::Allocator.
458
15768
MaybeLocal<Object> New(Environment* env,
459
                       char* data,
460
                       size_t length,
461
                       bool uses_malloc) {
462
15768
  if (length > 0) {
463
14906
    CHECK_NOT_NULL(data);
464
14906
    CHECK(length <= kMaxLength);
465
  }
466
467
15768
  if (uses_malloc) {
468
444
    if (!env->isolate_data()->uses_node_allocator()) {
469
      // We don't know for sure that the allocator is malloc()-based, so we need
470
      // to fall back to the FreeCallback variant.
471
      auto free_callback = [](char* data, void* hint) { free(data); };
472
      return New(env, data, length, free_callback, nullptr);
473
    } else {
474
      // This is malloc()-based, so we can acquire it into our own
475
      // ArrayBufferAllocator.
476
444
      CHECK_NOT_NULL(env->isolate_data()->node_allocator());
477
444
      env->isolate_data()->node_allocator()->RegisterPointer(data, length);
478
    }
479
  }
480
481
45936
  auto callback = [](void* data, size_t length, void* deleter_data){
482
15084
    CHECK_NOT_NULL(deleter_data);
483
484
15084
    static_cast<v8::ArrayBuffer::Allocator*>(deleter_data)
485
15084
        ->Free(data, length);
486
45936
  };
487
  std::unique_ptr<v8::BackingStore> backing =
488
      v8::ArrayBuffer::NewBackingStore(data,
489
                                       length,
490
                                       callback,
491
                                       env->isolate()
492
31536
                                          ->GetArrayBufferAllocator());
493
  Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(),
494
15768
                                           std::move(backing));
495
496
31536
  return Buffer::New(env, ab, 0, length).FromMaybe(Local<Object>());
497
}
498
499
namespace {
500
501
70
void CreateFromString(const FunctionCallbackInfo<Value>& args) {
502
210
  CHECK(args[0]->IsString());
503
140
  CHECK(args[1]->IsInt32());
504
505
210
  enum encoding enc = static_cast<enum encoding>(args[1].As<Int32>()->Value());
506
  Local<Object> buf;
507
210
  if (New(args.GetIsolate(), args[0].As<String>(), enc).ToLocal(&buf))
508
140
    args.GetReturnValue().Set(buf);
509
70
}
510
511
512
template <encoding encoding>
513
394474
void StringSlice(const FunctionCallbackInfo<Value>& args) {
514
394474
  Environment* env = Environment::GetCurrent(args);
515
394474
  Isolate* isolate = env->isolate();
516
517



394657
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
518
394474
  ArrayBufferViewContents<char> buffer(args.This());
519
520



394474
  if (buffer.length() == 0)
521
352
    return args.GetReturnValue().SetEmptyString();
522
523
394298
  size_t start = 0;
524
394298
  size_t end = 0;
525






1577192
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[0], 0, &start));
526






1971490
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], buffer.length(), &end));
527



394298
  if (end < start) end = start;
528






1182894
  THROW_AND_RETURN_IF_OOB(Just(end <= buffer.length()));
529
394298
  size_t length = end - start;
530
531
  Local<Value> error;
532
  MaybeLocal<Value> ret =
533
394298
      StringBytes::Encode(isolate,
534
394298
                          buffer.data() + start,
535
                          length,
536
                          encoding,
537
394298
                          &error);
538



394298
  if (ret.IsEmpty()) {
539



7
    CHECK(!error.IsEmpty());
540
7
    isolate->ThrowException(error);
541
7
    return;
542
  }
543
788582
  args.GetReturnValue().Set(ret.ToLocalChecked());
544
}
545
546
547
// bytesCopied = copy(buffer, target[, targetStart][, sourceStart][, sourceEnd])
548
13
void Copy(const FunctionCallbackInfo<Value> &args) {
549
13
  Environment* env = Environment::GetCurrent(args);
550
551
13
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
552
13
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
553
13
  ArrayBufferViewContents<char> source(args[0]);
554
26
  Local<Object> target_obj = args[1].As<Object>();
555

91
  SPREAD_BUFFER_ARG(target_obj, target);
556
557
13
  size_t target_start = 0;
558
13
  size_t source_start = 0;
559
13
  size_t source_end = 0;
560
561

52
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &target_start));
562

52
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &source_start));
563

65
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], source.length(),
564
                                          &source_end));
565
566
  // Copy 0 bytes; we're done
567

13
  if (target_start >= target_length || source_start >= source_end)
568
    return args.GetReturnValue().Set(0);
569
570
13
  if (source_start > source.length())
571
    return THROW_ERR_OUT_OF_RANGE(
572
        env, "The value of \"sourceStart\" is out of range.");
573
574
13
  if (source_end - source_start > target_length - target_start)
575
    source_end = source_start + target_length - target_start;
576
577
13
  uint32_t to_copy = std::min(
578
26
      std::min(source_end - source_start, target_length - target_start),
579
52
      source.length() - source_start);
580
581
13
  memmove(target_data + target_start, source.data() + source_start, to_copy);
582
26
  args.GetReturnValue().Set(to_copy);
583
}
584
585
586
160
void Fill(const FunctionCallbackInfo<Value>& args) {
587
160
  Environment* env = Environment::GetCurrent(args);
588
160
  Local<Context> ctx = env->context();
589
590
185
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
591

1415
  SPREAD_BUFFER_ARG(args[0], ts_obj);
592
593
  size_t start;
594

640
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &start));
595
  size_t end;
596

636
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &end));
597
598
158
  size_t fill_length = end - start;
599
  Local<String> str_obj;
600
  size_t str_length;
601
  enum encoding enc;
602
603
  // OOB Check. Throw the error in JS.
604

158
  if (start > end || fill_length + start > ts_obj_length)
605
    return args.GetReturnValue().Set(-2);
606
607
  // First check if Buffer has been passed.
608
158
  if (Buffer::HasInstance(args[1])) {
609

63
    SPREAD_BUFFER_ARG(args[1], fill_obj);
610
7
    str_length = fill_obj_length;
611
14
    memcpy(
612
21
        ts_obj_data + start, fill_obj_data, std::min(str_length, fill_length));
613
7
    goto start_fill;
614
  }
615
616
  // Then coerce everything that's not a string.
617
453
  if (!args[1]->IsString()) {
618
    uint32_t val;
619
9
    if (!args[1]->Uint32Value(ctx).To(&val)) return;
620
3
    int value = val & 255;
621
3
    memset(ts_obj_data + start, value, fill_length);
622
3
    return;
623
  }
624
625
592
  str_obj = args[1]->ToString(env->context()).ToLocalChecked();
626
148
  enc = ParseEncoding(env->isolate(), args[4], UTF8);
627
628
  // Can't use StringBytes::Write() in all cases. For example if attempting
629
  // to write a two byte character into a one byte Buffer.
630
148
  if (enc == UTF8) {
631
96
    str_length = str_obj->Utf8Length(env->isolate());
632
96
    node::Utf8Value str(env->isolate(), args[1]);
633
48
    memcpy(ts_obj_data + start, *str, std::min(str_length, fill_length));
634
635
100
  } else if (enc == UCS2) {
636
39
    str_length = str_obj->Length() * sizeof(uint16_t);
637
78
    node::TwoByteValue str(env->isolate(), args[1]);
638
39
    if (IsBigEndian())
639
      SwapBytes16(reinterpret_cast<char*>(&str[0]), str_length);
640
641
39
    memcpy(ts_obj_data + start, *str, std::min(str_length, fill_length));
642
643
  } else {
644
    // Write initial String to Buffer, then use that memory to copy remainder
645
    // of string. Correct the string length for cases like HEX where less than
646
    // the total string length is written.
647
122
    str_length = StringBytes::Write(env->isolate(),
648
61
                                    ts_obj_data + start,
649
                                    fill_length,
650
                                    str_obj,
651
                                    enc,
652
                                    nullptr);
653
  }
654
655
 start_fill:
656
657
155
  if (str_length >= fill_length)
658
14
    return;
659
660
  // If str_length is zero, then either an empty buffer was provided, or Write()
661
  // indicated that no bytes could be written. If no bytes could be written,
662
  // then return -1 because the fill value is invalid. This will trigger a throw
663
  // in JavaScript. Silently failing should be avoided because it can lead to
664
  // buffers with unexpected contents.
665
141
  if (str_length == 0)
666
12
    return args.GetReturnValue().Set(-1);
667
668
135
  size_t in_there = str_length;
669
135
  char* ptr = ts_obj_data + start + str_length;
670
671
593
  while (in_there < fill_length - in_there) {
672
229
    memcpy(ptr, ts_obj_data + start, in_there);
673
229
    ptr += in_there;
674
229
    in_there *= 2;
675
  }
676
677
135
  if (in_there < fill_length) {
678
135
    memcpy(ptr, ts_obj_data + start, fill_length - in_there);
679
  }
680
}
681
682
683
template <encoding encoding>
684
434509
void StringWrite(const FunctionCallbackInfo<Value>& args) {
685
434509
  Environment* env = Environment::GetCurrent(args);
686
687



434513
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
688









3910577
  SPREAD_BUFFER_ARG(args.This(), ts_obj);
689
690



1303527
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "argument");
691
692
1738036
  Local<String> str = args[0]->ToString(env->context()).ToLocalChecked();
693
694
  size_t offset;
695
  size_t max_length;
696
697






1738036
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], 0, &offset));
698



434509
  if (offset > ts_obj_length) {
699
    return node::THROW_ERR_BUFFER_OUT_OF_BOUNDS(
700
        env, "\"offset\" is outside of buffer bounds");
701
  }
702
703






2172545
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], ts_obj_length - offset,
704
                                          &max_length));
705
706
434509
  max_length = std::min(ts_obj_length - offset, max_length);
707
708



434509
  if (max_length == 0)
709
8
    return args.GetReturnValue().Set(0);
710
711
1303515
  uint32_t written = StringBytes::Write(env->isolate(),
712
434505
                                        ts_obj_data + offset,
713
                                        max_length,
714
                                        str,
715
                                        encoding,
716
434505
                                        nullptr);
717



869010
  args.GetReturnValue().Set(written);
718
}
719
720
125480
void ByteLengthUtf8(const FunctionCallbackInfo<Value> &args) {
721
125480
  Environment* env = Environment::GetCurrent(args);
722
376440
  CHECK(args[0]->IsString());
723
724
  // Fast case: avoid StringBytes on UTF8 string. Jump to v8.
725
752880
  args.GetReturnValue().Set(args[0].As<String>()->Utf8Length(env->isolate()));
726
125480
}
727
728
// Normalize val to be an integer in the range of [1, -1] since
729
// implementations of memcmp() can vary by platform.
730
2937
static int normalizeCompareVal(int val, size_t a_length, size_t b_length) {
731
2937
  if (val == 0) {
732
2910
    if (a_length > b_length)
733
6
      return 1;
734
2904
    else if (a_length < b_length)
735
5
      return -1;
736
  } else {
737
27
    if (val > 0)
738
7
      return 1;
739
    else
740
20
      return -1;
741
  }
742
2899
  return val;
743
}
744
745
9
void CompareOffset(const FunctionCallbackInfo<Value> &args) {
746
9
  Environment* env = Environment::GetCurrent(args);
747
748
9
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
749
9
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
750
9
  ArrayBufferViewContents<char> source(args[0]);
751
9
  ArrayBufferViewContents<char> target(args[1]);
752
753
9
  size_t target_start = 0;
754
9
  size_t source_start = 0;
755
9
  size_t source_end = 0;
756
9
  size_t target_end = 0;
757
758

36
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &target_start));
759

36
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &source_start));
760

45
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], target.length(),
761
                                          &target_end));
762

45
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[5], source.length(),
763
                                          &source_end));
764
765
9
  if (source_start > source.length())
766
    return THROW_ERR_OUT_OF_RANGE(
767
        env, "The value of \"sourceStart\" is out of range.");
768
9
  if (target_start > target.length())
769
    return THROW_ERR_OUT_OF_RANGE(
770
        env, "The value of \"targetStart\" is out of range.");
771
772
9
  CHECK_LE(source_start, source_end);
773
9
  CHECK_LE(target_start, target_end);
774
775
  size_t to_cmp =
776
18
      std::min(std::min(source_end - source_start, target_end - target_start),
777
27
               source.length() - source_start);
778
779
18
  int val = normalizeCompareVal(to_cmp > 0 ?
780
9
                                  memcmp(source.data() + source_start,
781
9
                                         target.data() + target_start,
782
                                         to_cmp) : 0,
783
                                source_end - source_start,
784
9
                                target_end - target_start);
785
786
18
  args.GetReturnValue().Set(val);
787
}
788
789
2928
void Compare(const FunctionCallbackInfo<Value> &args) {
790
2928
  Environment* env = Environment::GetCurrent(args);
791
792
2928
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
793
2928
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
794
2928
  ArrayBufferViewContents<char> a(args[0]);
795
2928
  ArrayBufferViewContents<char> b(args[1]);
796
797
2928
  size_t cmp_length = std::min(a.length(), b.length());
798
799
5797
  int val = normalizeCompareVal(cmp_length > 0 ?
800
2869
                                memcmp(a.data(), b.data(), cmp_length) : 0,
801
2928
                                a.length(), b.length());
802
5856
  args.GetReturnValue().Set(val);
803
}
804
805
806
// Computes the offset for starting an indexOf or lastIndexOf search.
807
// Returns either a valid offset in [0...<length - 1>], ie inside the Buffer,
808
// or -1 to signal that there is no possible match.
809
4853
int64_t IndexOfOffset(size_t length,
810
                      int64_t offset_i64,
811
                      int64_t needle_length,
812
                      bool is_forward) {
813
4853
  int64_t length_i64 = static_cast<int64_t>(length);
814
4853
  if (offset_i64 < 0) {
815
77
    if (offset_i64 + length_i64 >= 0) {
816
      // Negative offsets count backwards from the end of the buffer.
817
59
      return length_i64 + offset_i64;
818

18
    } else if (is_forward || needle_length == 0) {
819
      // indexOf from before the start of the buffer: search the whole buffer.
820
10
      return 0;
821
    } else {
822
      // lastIndexOf from before the start of the buffer: no match.
823
8
      return -1;
824
    }
825
  } else {
826
4776
    if (offset_i64 + needle_length <= length_i64) {
827
      // Valid positive offset.
828
4688
      return offset_i64;
829
88
    } else if (needle_length == 0) {
830
      // Out of buffer bounds, but empty needle: point to end of buffer.
831
10
      return length_i64;
832
78
    } else if (is_forward) {
833
      // indexOf from past the end of the buffer: no match.
834
15
      return -1;
835
    } else {
836
      // lastIndexOf from past the end of the buffer: search the whole buffer.
837
63
      return length_i64 - 1;
838
    }
839
  }
840
}
841
842
890
void IndexOfString(const FunctionCallbackInfo<Value>& args) {
843
890
  Environment* env = Environment::GetCurrent(args);
844
890
  Isolate* isolate = env->isolate();
845
846
2670
  CHECK(args[1]->IsString());
847
1780
  CHECK(args[2]->IsNumber());
848
1780
  CHECK(args[3]->IsInt32());
849
1780
  CHECK(args[4]->IsBoolean());
850
851
2670
  enum encoding enc = static_cast<enum encoding>(args[3].As<Int32>()->Value());
852
853
923
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
854
890
  ArrayBufferViewContents<char> buffer(args[0]);
855
856
1780
  Local<String> needle = args[1].As<String>();
857
2670
  int64_t offset_i64 = args[2].As<Integer>()->Value();
858
1780
  bool is_forward = args[4]->IsTrue();
859
860
890
  const char* haystack = buffer.data();
861
  // Round down to the nearest multiple of 2 in case of UCS2.
862
980
  const size_t haystack_length = (enc == UCS2) ?
863
980
      buffer.length() &~ 1 : buffer.length();  // NOLINT(whitespace/operators)
864
865
  size_t needle_length;
866
1780
  if (!StringBytes::Size(isolate, needle, enc).To(&needle_length)) return;
867
868
890
  int64_t opt_offset = IndexOfOffset(haystack_length,
869
                                     offset_i64,
870
                                     needle_length,
871
890
                                     is_forward);
872
873
890
  if (needle_length == 0) {
874
    // Match String#indexOf() and String#lastIndexOf() behavior.
875
24
    args.GetReturnValue().Set(static_cast<double>(opt_offset));
876
8
    return;
877
  }
878
879
882
  if (haystack_length == 0) {
880
    return args.GetReturnValue().Set(-1);
881
  }
882
883
882
  if (opt_offset <= -1) {
884
20
    return args.GetReturnValue().Set(-1);
885
  }
886
872
  size_t offset = static_cast<size_t>(opt_offset);
887
872
  CHECK_LT(offset, haystack_length);
888

1742
  if ((is_forward && needle_length + offset > haystack_length) ||
889
870
      needle_length > haystack_length) {
890
30
    return args.GetReturnValue().Set(-1);
891
  }
892
893
857
  size_t result = haystack_length;
894
895
857
  if (enc == UCS2) {
896
170
    String::Value needle_value(isolate, needle);
897
85
    if (*needle_value == nullptr)
898
      return args.GetReturnValue().Set(-1);
899
900

85
    if (haystack_length < 2 || needle_value.length() < 1) {
901
      return args.GetReturnValue().Set(-1);
902
    }
903
904
85
    if (IsBigEndian()) {
905
      StringBytes::InlineDecoder decoder;
906
      if (decoder.Decode(env, needle, enc).IsNothing()) return;
907
      const uint16_t* decoded_string =
908
          reinterpret_cast<const uint16_t*>(decoder.out());
909
910
      if (decoded_string == nullptr)
911
        return args.GetReturnValue().Set(-1);
912
913
      result = SearchString(reinterpret_cast<const uint16_t*>(haystack),
914
                            haystack_length / 2,
915
                            decoded_string,
916
                            decoder.size() / 2,
917
                            offset / 2,
918
                            is_forward);
919
    } else {
920
255
      result = SearchString(reinterpret_cast<const uint16_t*>(haystack),
921
                            haystack_length / 2,
922
85
                            reinterpret_cast<const uint16_t*>(*needle_value),
923
85
                            needle_value.length(),
924
                            offset / 2,
925
85
                            is_forward);
926
    }
927
85
    result *= 2;
928
772
  } else if (enc == UTF8) {
929
1520
    String::Utf8Value needle_value(isolate, needle);
930
760
    if (*needle_value == nullptr)
931
      return args.GetReturnValue().Set(-1);
932
933
1520
    result = SearchString(reinterpret_cast<const uint8_t*>(haystack),
934
                          haystack_length,
935
760
                          reinterpret_cast<const uint8_t*>(*needle_value),
936
                          needle_length,
937
                          offset,
938
760
                          is_forward);
939
12
  } else if (enc == LATIN1) {
940
12
    uint8_t* needle_data = node::UncheckedMalloc<uint8_t>(needle_length);
941
12
    if (needle_data == nullptr) {
942
      return args.GetReturnValue().Set(-1);
943
    }
944
24
    needle->WriteOneByte(
945
12
        isolate, needle_data, 0, needle_length, String::NO_NULL_TERMINATION);
946
947
12
    result = SearchString(reinterpret_cast<const uint8_t*>(haystack),
948
                          haystack_length,
949
                          needle_data,
950
                          needle_length,
951
                          offset,
952
12
                          is_forward);
953
12
    free(needle_data);
954
  }
955
956
2571
  args.GetReturnValue().Set(
957
857
      result == haystack_length ? -1 : static_cast<int>(result));
958
}
959
960
218
void IndexOfBuffer(const FunctionCallbackInfo<Value>& args) {
961
436
  CHECK(args[1]->IsObject());
962
436
  CHECK(args[2]->IsNumber());
963
436
  CHECK(args[3]->IsInt32());
964
436
  CHECK(args[4]->IsBoolean());
965
966
654
  enum encoding enc = static_cast<enum encoding>(args[3].As<Int32>()->Value());
967
968
248
  THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[0]);
969
218
  THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[1]);
970
218
  ArrayBufferViewContents<char> haystack_contents(args[0]);
971
218
  ArrayBufferViewContents<char> needle_contents(args[1]);
972
654
  int64_t offset_i64 = args[2].As<Integer>()->Value();
973
436
  bool is_forward = args[4]->IsTrue();
974
975
218
  const char* haystack = haystack_contents.data();
976
218
  const size_t haystack_length = haystack_contents.length();
977
218
  const char* needle = needle_contents.data();
978
218
  const size_t needle_length = needle_contents.length();
979
980
218
  int64_t opt_offset = IndexOfOffset(haystack_length,
981
                                     offset_i64,
982
                                     needle_length,
983
218
                                     is_forward);
984
985
218
  if (needle_length == 0) {
986
    // Match String#indexOf() and String#lastIndexOf() behavior.
987
36
    args.GetReturnValue().Set(static_cast<double>(opt_offset));
988
12
    return;
989
  }
990
991
206
  if (haystack_length == 0) {
992
    return args.GetReturnValue().Set(-1);
993
  }
994
995
206
  if (opt_offset <= -1) {
996
18
    return args.GetReturnValue().Set(-1);
997
  }
998
197
  size_t offset = static_cast<size_t>(opt_offset);
999
197
  CHECK_LT(offset, haystack_length);
1000

392
  if ((is_forward && needle_length + offset > haystack_length) ||
1001
195
      needle_length > haystack_length) {
1002
14
    return args.GetReturnValue().Set(-1);
1003
  }
1004
1005
190
  size_t result = haystack_length;
1006
1007
190
  if (enc == UCS2) {
1008

58
    if (haystack_length < 2 || needle_length < 2) {
1009
4
      return args.GetReturnValue().Set(-1);
1010
    }
1011
56
    result = SearchString(
1012
        reinterpret_cast<const uint16_t*>(haystack),
1013
        haystack_length / 2,
1014
        reinterpret_cast<const uint16_t*>(needle),
1015
        needle_length / 2,
1016
        offset / 2,
1017
56
        is_forward);
1018
56
    result *= 2;
1019
  } else {
1020
132
    result = SearchString(
1021
        reinterpret_cast<const uint8_t*>(haystack),
1022
        haystack_length,
1023
        reinterpret_cast<const uint8_t*>(needle),
1024
        needle_length,
1025
        offset,
1026
132
        is_forward);
1027
  }
1028
1029
564
  args.GetReturnValue().Set(
1030
188
      result == haystack_length ? -1 : static_cast<int>(result));
1031
}
1032
1033
3746
void IndexOfNumber(const FunctionCallbackInfo<Value>& args) {
1034
7492
  CHECK(args[1]->IsUint32());
1035
7492
  CHECK(args[2]->IsNumber());
1036
7492
  CHECK(args[3]->IsBoolean());
1037
1038
3751
  THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[0]);
1039
3745
  ArrayBufferViewContents<char> buffer(args[0]);
1040
1041
11235
  uint32_t needle = args[1].As<Uint32>()->Value();
1042
11235
  int64_t offset_i64 = args[2].As<Integer>()->Value();
1043
7490
  bool is_forward = args[3]->IsTrue();
1044
1045
  int64_t opt_offset =
1046
3745
      IndexOfOffset(buffer.length(), offset_i64, 1, is_forward);
1047

3745
  if (opt_offset <= -1 || buffer.length() == 0) {
1048
8
    return args.GetReturnValue().Set(-1);
1049
  }
1050
3741
  size_t offset = static_cast<size_t>(opt_offset);
1051
3741
  CHECK_LT(offset, buffer.length());
1052
1053
  const void* ptr;
1054
3741
  if (is_forward) {
1055
3733
    ptr = memchr(buffer.data() + offset, needle, buffer.length() - offset);
1056
  } else {
1057
8
    ptr = node::stringsearch::MemrchrFill(buffer.data(), needle, offset + 1);
1058
  }
1059
3741
  const char* ptr_char = static_cast<const char*>(ptr);
1060
11223
  args.GetReturnValue().Set(ptr ? static_cast<int>(ptr_char - buffer.data())
1061
                                : -1);
1062
}
1063
1064
1065
2
void Swap16(const FunctionCallbackInfo<Value>& args) {
1066
2
  Environment* env = Environment::GetCurrent(args);
1067
2
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1068

18
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1069
2
  SwapBytes16(ts_obj_data, ts_obj_length);
1070
4
  args.GetReturnValue().Set(args[0]);
1071
}
1072
1073
1074
2
void Swap32(const FunctionCallbackInfo<Value>& args) {
1075
2
  Environment* env = Environment::GetCurrent(args);
1076
2
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1077

18
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1078
2
  SwapBytes32(ts_obj_data, ts_obj_length);
1079
4
  args.GetReturnValue().Set(args[0]);
1080
}
1081
1082
1083
2
void Swap64(const FunctionCallbackInfo<Value>& args) {
1084
2
  Environment* env = Environment::GetCurrent(args);
1085
2
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1086

18
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1087
2
  SwapBytes64(ts_obj_data, ts_obj_length);
1088
4
  args.GetReturnValue().Set(args[0]);
1089
}
1090
1091
1092
// Encode a single string to a UTF-8 Uint8Array (not Buffer).
1093
// Used in TextEncoder.prototype.encode.
1094
21
static void EncodeUtf8String(const FunctionCallbackInfo<Value>& args) {
1095
21
  Environment* env = Environment::GetCurrent(args);
1096
21
  Isolate* isolate = env->isolate();
1097
21
  CHECK_GE(args.Length(), 1);
1098
63
  CHECK(args[0]->IsString());
1099
1100
42
  Local<String> str = args[0].As<String>();
1101
21
  size_t length = str->Utf8Length(isolate);
1102
42
  AllocatedBuffer buf = env->AllocateManaged(length);
1103
42
  str->WriteUtf8(isolate,
1104
                 buf.data(),
1105
                 -1,  // We are certain that `data` is sufficiently large
1106
                 nullptr,
1107
21
                 String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8);
1108
21
  auto array = Uint8Array::New(buf.ToArrayBuffer(), 0, length);
1109
42
  args.GetReturnValue().Set(array);
1110
21
}
1111
1112
1113
45
static void EncodeInto(const FunctionCallbackInfo<Value>& args) {
1114
45
  Environment* env = Environment::GetCurrent(args);
1115
45
  Isolate* isolate = env->isolate();
1116
45
  CHECK_GE(args.Length(), 3);
1117
135
  CHECK(args[0]->IsString());
1118
90
  CHECK(args[1]->IsUint8Array());
1119
90
  CHECK(args[2]->IsUint32Array());
1120
1121
90
  Local<String> source = args[0].As<String>();
1122
1123
90
  Local<Uint8Array> dest = args[1].As<Uint8Array>();
1124
45
  Local<ArrayBuffer> buf = dest->Buffer();
1125
  char* write_result =
1126
90
      static_cast<char*>(buf->GetBackingStore()->Data()) + dest->ByteOffset();
1127
45
  size_t dest_length = dest->ByteLength();
1128
1129
  // results = [ read, written ]
1130
90
  Local<Uint32Array> result_arr = args[2].As<Uint32Array>();
1131
  uint32_t* results = reinterpret_cast<uint32_t*>(
1132
135
      static_cast<char*>(result_arr->Buffer()->GetBackingStore()->Data()) +
1133
45
      result_arr->ByteOffset());
1134
1135
  int nchars;
1136
90
  int written = source->WriteUtf8(
1137
      isolate,
1138
      write_result,
1139
      dest_length,
1140
      &nchars,
1141
45
      String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8);
1142
45
  results[0] = nchars;
1143
45
  results[1] = written;
1144
45
}
1145
1146
1147
4377
void SetBufferPrototype(const FunctionCallbackInfo<Value>& args) {
1148
4377
  Environment* env = Environment::GetCurrent(args);
1149
1150
8754
  CHECK(args[0]->IsObject());
1151
8754
  Local<Object> proto = args[0].As<Object>();
1152
4377
  env->set_buffer_prototype_object(proto);
1153
4377
}
1154
1155
1156
4377
void Initialize(Local<Object> target,
1157
                Local<Value> unused,
1158
                Local<Context> context,
1159
                void* priv) {
1160
4377
  Environment* env = Environment::GetCurrent(context);
1161
1162
4377
  env->SetMethod(target, "setBufferPrototype", SetBufferPrototype);
1163
4377
  env->SetMethodNoSideEffect(target, "createFromString", CreateFromString);
1164
1165
4377
  env->SetMethodNoSideEffect(target, "byteLengthUtf8", ByteLengthUtf8);
1166
4377
  env->SetMethod(target, "copy", Copy);
1167
4377
  env->SetMethodNoSideEffect(target, "compare", Compare);
1168
4377
  env->SetMethodNoSideEffect(target, "compareOffset", CompareOffset);
1169
4377
  env->SetMethod(target, "fill", Fill);
1170
4377
  env->SetMethodNoSideEffect(target, "indexOfBuffer", IndexOfBuffer);
1171
4377
  env->SetMethodNoSideEffect(target, "indexOfNumber", IndexOfNumber);
1172
4377
  env->SetMethodNoSideEffect(target, "indexOfString", IndexOfString);
1173
1174
4377
  env->SetMethod(target, "swap16", Swap16);
1175
4377
  env->SetMethod(target, "swap32", Swap32);
1176
4377
  env->SetMethod(target, "swap64", Swap64);
1177
1178
4377
  env->SetMethod(target, "encodeInto", EncodeInto);
1179
4377
  env->SetMethodNoSideEffect(target, "encodeUtf8String", EncodeUtf8String);
1180
1181
8754
  target->Set(env->context(),
1182
              FIXED_ONE_BYTE_STRING(env->isolate(), "kMaxLength"),
1183
21885
              Number::New(env->isolate(), kMaxLength)).Check();
1184
1185
8754
  target->Set(env->context(),
1186
              FIXED_ONE_BYTE_STRING(env->isolate(), "kStringMaxLength"),
1187
21885
              Integer::New(env->isolate(), String::kMaxLength)).Check();
1188
1189
4377
  env->SetMethodNoSideEffect(target, "asciiSlice", StringSlice<ASCII>);
1190
4377
  env->SetMethodNoSideEffect(target, "base64Slice", StringSlice<BASE64>);
1191
4377
  env->SetMethodNoSideEffect(target, "latin1Slice", StringSlice<LATIN1>);
1192
4377
  env->SetMethodNoSideEffect(target, "hexSlice", StringSlice<HEX>);
1193
4377
  env->SetMethodNoSideEffect(target, "ucs2Slice", StringSlice<UCS2>);
1194
4377
  env->SetMethodNoSideEffect(target, "utf8Slice", StringSlice<UTF8>);
1195
1196
4377
  env->SetMethod(target, "asciiWrite", StringWrite<ASCII>);
1197
4377
  env->SetMethod(target, "base64Write", StringWrite<BASE64>);
1198
4377
  env->SetMethod(target, "latin1Write", StringWrite<LATIN1>);
1199
4377
  env->SetMethod(target, "hexWrite", StringWrite<HEX>);
1200
4377
  env->SetMethod(target, "ucs2Write", StringWrite<UCS2>);
1201
4377
  env->SetMethod(target, "utf8Write", StringWrite<UTF8>);
1202
1203
  // It can be a nullptr when running inside an isolate where we
1204
  // do not own the ArrayBuffer allocator.
1205
4377
  if (NodeArrayBufferAllocator* allocator =
1206
4377
          env->isolate_data()->node_allocator()) {
1207
4351
    uint32_t* zero_fill_field = allocator->zero_fill_field();
1208
    std::unique_ptr<BackingStore> backing =
1209
      ArrayBuffer::NewBackingStore(zero_fill_field,
1210
                                   sizeof(*zero_fill_field),
1211
12243
                                   [](void*, size_t, void*){},
1212
8702
                                   nullptr);
1213
    Local<ArrayBuffer> array_buffer =
1214
4351
        ArrayBuffer::New(env->isolate(), std::move(backing));
1215
    // TODO(thangktran): drop this check when V8 is pumped to 8.0 .
1216
4351
    if (!array_buffer->IsExternal())
1217
8702
      array_buffer->Externalize(array_buffer->GetBackingStore());
1218
8702
    array_buffer->SetPrivate(
1219
        env->context(),
1220
        env->arraybuffer_untransferable_private_symbol(),
1221
13053
        True(env->isolate())).Check();
1222
21755
    CHECK(target
1223
              ->Set(env->context(),
1224
                    FIXED_ONE_BYTE_STRING(env->isolate(), "zeroFill"),
1225
                    Uint32Array::New(array_buffer, 0, 1))
1226
              .FromJust());
1227
  }
1228
4377
}
1229
1230
}  // anonymous namespace
1231
}  // namespace Buffer
1232
}  // namespace node
1233
1234
4185
NODE_MODULE_CONTEXT_AWARE_INTERNAL(buffer, node::Buffer::Initialize)