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: 598 655 91.3 %
Date: 2021-04-16 04:11:37 Branches: 422 712 59.3 %

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 "allocated_buffer-inl.h"
24
#include "node.h"
25
#include "node_blob.h"
26
#include "node_errors.h"
27
#include "node_external_reference.h"
28
#include "node_internals.h"
29
30
#include "env-inl.h"
31
#include "string_bytes.h"
32
#include "string_search.h"
33
#include "util-inl.h"
34
#include "v8.h"
35
36
#include <cstring>
37
#include <climits>
38
39
#define THROW_AND_RETURN_UNLESS_BUFFER(env, obj)                            \
40
  THROW_AND_RETURN_IF_NOT_BUFFER(env, obj, "argument")                      \
41
42
#define THROW_AND_RETURN_IF_OOB(r)                                          \
43
  do {                                                                      \
44
    if ((r).IsNothing()) return;                                            \
45
    if (!(r).FromJust())                                                    \
46
      return node::THROW_ERR_OUT_OF_RANGE(env, "Index out of range");       \
47
  } while (0)                                                               \
48
49
namespace node {
50
namespace Buffer {
51
52
using v8::ArrayBuffer;
53
using v8::ArrayBufferView;
54
using v8::BackingStore;
55
using v8::Context;
56
using v8::EscapableHandleScope;
57
using v8::FunctionCallbackInfo;
58
using v8::Global;
59
using v8::HandleScope;
60
using v8::Int32;
61
using v8::Integer;
62
using v8::Isolate;
63
using v8::Just;
64
using v8::Local;
65
using v8::Maybe;
66
using v8::MaybeLocal;
67
using v8::Nothing;
68
using v8::Number;
69
using v8::Object;
70
using v8::String;
71
using v8::Uint32;
72
using v8::Uint32Array;
73
using v8::Uint8Array;
74
using v8::Value;
75
76
namespace {
77
78
1036
class CallbackInfo {
79
 public:
80
  static inline Local<ArrayBuffer> CreateTrackedArrayBuffer(
81
      Environment* env,
82
      char* data,
83
      size_t length,
84
      FreeCallback callback,
85
      void* hint);
86
87
  CallbackInfo(const CallbackInfo&) = delete;
88
  CallbackInfo& operator=(const CallbackInfo&) = delete;
89
90
 private:
91
  static void CleanupHook(void* data);
92
  inline void OnBackingStoreFree();
93
  inline void CallAndResetCallback();
94
  inline CallbackInfo(Environment* env,
95
                      FreeCallback callback,
96
                      char* data,
97
                      void* hint);
98
  Global<ArrayBuffer> persistent_;
99
  Mutex mutex_;  // Protects callback_.
100
  FreeCallback callback_;
101
  char* const data_;
102
  void* const hint_;
103
  Environment* const env_;
104
};
105
106
107
531
Local<ArrayBuffer> CallbackInfo::CreateTrackedArrayBuffer(
108
    Environment* env,
109
    char* data,
110
    size_t length,
111
    FreeCallback callback,
112
    void* hint) {
113
531
  CHECK_NOT_NULL(callback);
114

531
  CHECK_IMPLIES(data == nullptr, length == 0);
115
116
531
  CallbackInfo* self = new CallbackInfo(env, callback, data, hint);
117
  std::unique_ptr<BackingStore> bs =
118
1567
      ArrayBuffer::NewBackingStore(data, length, [](void*, size_t, void* arg) {
119
518
        static_cast<CallbackInfo*>(arg)->OnBackingStoreFree();
120
2629
      }, self);
121
531
  Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(bs));
122
123
  // V8 simply ignores the BackingStore deleter callback if data == nullptr,
124
  // but our API contract requires it being called.
125
531
  if (data == nullptr) {
126
4
    ab->Detach();
127
4
    self->OnBackingStoreFree();  // This calls `callback` asynchronously.
128
  } else {
129
    // Store the ArrayBuffer so that we can detach it later.
130
527
    self->persistent_.Reset(env->isolate(), ab);
131
527
    self->persistent_.SetWeak();
132
  }
133
134
1062
  return ab;
135
}
136
137
138
531
CallbackInfo::CallbackInfo(Environment* env,
139
                           FreeCallback callback,
140
                           char* data,
141
531
                           void* hint)
142
    : callback_(callback),
143
      data_(data),
144
      hint_(hint),
145
1062
      env_(env) {
146
531
  env->AddCleanupHook(CleanupHook, this);
147
531
  env->isolate()->AdjustAmountOfExternalAllocatedMemory(sizeof(*this));
148
531
}
149
150
220
void CallbackInfo::CleanupHook(void* data) {
151
220
  CallbackInfo* self = static_cast<CallbackInfo*>(data);
152
153
  {
154
440
    HandleScope handle_scope(self->env_->isolate());
155
440
    Local<ArrayBuffer> ab = self->persistent_.Get(self->env_->isolate());
156

440
    if (!ab.IsEmpty() && ab->IsDetachable()) {
157
220
      ab->Detach();
158
220
      self->persistent_.Reset();
159
    }
160
  }
161
162
  // Call the callback in this case, but don't delete `this` yet because the
163
  // BackingStore deleter callback will do so later.
164
220
  self->CallAndResetCallback();
165
220
}
166
167
738
void CallbackInfo::CallAndResetCallback() {
168
  FreeCallback callback;
169
  {
170
1476
    Mutex::ScopedLock lock(mutex_);
171
738
    callback = callback_;
172
738
    callback_ = nullptr;
173
  }
174
738
  if (callback != nullptr) {
175
    // Clean up all Environment-related state and run the callback.
176
518
    env_->RemoveCleanupHook(CleanupHook, this);
177
518
    int64_t change_in_bytes = -static_cast<int64_t>(sizeof(*this));
178
518
    env_->isolate()->AdjustAmountOfExternalAllocatedMemory(change_in_bytes);
179
180
518
    callback(data_, hint_);
181
  }
182
738
}
183
184
522
void CallbackInfo::OnBackingStoreFree() {
185
  // This method should always release the memory for `this`.
186
1044
  std::unique_ptr<CallbackInfo> self { this };
187
1044
  Mutex::ScopedLock lock(mutex_);
188
  // If callback_ == nullptr, that means that the callback has already run from
189
  // the cleanup hook, and there is nothing left to do here besides to clean
190
  // up the memory involved. In particular, the underlying `Environment` may
191
  // be gone at this point, so don’t attempt to call SetImmediateThreadsafe().
192
522
  if (callback_ == nullptr) return;
193
194
3124
  env_->SetImmediateThreadsafe([self = std::move(self)](Environment* env) {
195
518
    CHECK_EQ(self->env_, env);  // Consistency check.
196
197
518
    self->CallAndResetCallback();
198
1040
  });
199
}
200
201
202
// Parse index for external array data. An empty Maybe indicates
203
// a pending exception. `false` indicates that the index is out-of-bounds.
204
1107189
inline MUST_USE_RESULT Maybe<bool> ParseArrayIndex(Environment* env,
205
                                                   Local<Value> arg,
206
                                                   size_t def,
207
                                                   size_t* ret) {
208
2214378
  if (arg->IsUndefined()) {
209
    *ret = def;
210
    return Just(true);
211
  }
212
213
  int64_t tmp_i;
214
3321562
  if (!arg->IntegerValue(env->context()).To(&tmp_i))
215
    return Nothing<bool>();
216
217
1107185
  if (tmp_i < 0)
218
4
    return Just(false);
219
220
  // Check that the result fits in a size_t.
221
1107181
  const uint64_t kSizeMax = static_cast<uint64_t>(static_cast<size_t>(-1));
222
  // coverity[pointless_expression]
223
  if (static_cast<uint64_t>(tmp_i) > kSizeMax)
224
    return Just(false);
225
226
1107181
  *ret = static_cast<size_t>(tmp_i);
227
1107181
  return Just(true);
228
}
229
230
}  // anonymous namespace
231
232
// Buffer methods
233
234
3639038
bool HasInstance(Local<Value> val) {
235
3639038
  return val->IsArrayBufferView();
236
}
237
238
239
276769
bool HasInstance(Local<Object> obj) {
240
276769
  return obj->IsArrayBufferView();
241
}
242
243
244
247428
char* Data(Local<Value> val) {
245
247428
  CHECK(val->IsArrayBufferView());
246
247428
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
247
742283
  return static_cast<char*>(ui->Buffer()->GetBackingStore()->Data()) +
248
494856
      ui->ByteOffset();
249
}
250
251
252
116513
char* Data(Local<Object> obj) {
253
116513
  return Data(obj.As<Value>());
254
}
255
256
257
103274
size_t Length(Local<Value> val) {
258
103274
  CHECK(val->IsArrayBufferView());
259
103274
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
260
103274
  return ui->ByteLength();
261
}
262
263
264
115142
size_t Length(Local<Object> obj) {
265
115142
  CHECK(obj->IsArrayBufferView());
266
115142
  Local<ArrayBufferView> ui = obj.As<ArrayBufferView>();
267
115142
  return ui->ByteLength();
268
}
269
270
271
13308
MaybeLocal<Uint8Array> New(Environment* env,
272
                           Local<ArrayBuffer> ab,
273
                           size_t byte_offset,
274
                           size_t length) {
275
26616
  CHECK(!env->buffer_prototype_object().IsEmpty());
276
13308
  Local<Uint8Array> ui = Uint8Array::New(ab, byte_offset, length);
277
  Maybe<bool> mb =
278
39924
      ui->SetPrototype(env->context(), env->buffer_prototype_object());
279
13308
  if (mb.IsNothing())
280
    return MaybeLocal<Uint8Array>();
281
13308
  return ui;
282
}
283
284
MaybeLocal<Uint8Array> New(Isolate* isolate,
285
                           Local<ArrayBuffer> ab,
286
                           size_t byte_offset,
287
                           size_t length) {
288
  Environment* env = Environment::GetCurrent(isolate);
289
  if (env == nullptr) {
290
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
291
    return MaybeLocal<Uint8Array>();
292
  }
293
  return New(env, ab, byte_offset, length);
294
}
295
296
297
134
MaybeLocal<Object> New(Isolate* isolate,
298
                       Local<String> string,
299
                       enum encoding enc) {
300
134
  EscapableHandleScope scope(isolate);
301
302
  size_t length;
303
268
  if (!StringBytes::Size(isolate, string, enc).To(&length))
304
    return Local<Object>();
305
134
  size_t actual = 0;
306
134
  char* data = nullptr;
307
308
134
  if (length > 0) {
309
134
    data = UncheckedMalloc(length);
310
311
134
    if (data == nullptr) {
312
      THROW_ERR_MEMORY_ALLOCATION_FAILED(isolate);
313
      return Local<Object>();
314
    }
315
316
134
    actual = StringBytes::Write(isolate, data, length, string, enc);
317
134
    CHECK(actual <= length);
318
319
134
    if (actual == 0) {
320
1
      free(data);
321
1
      data = nullptr;
322
133
    } else if (actual < length) {
323
      data = node::Realloc(data, actual);
324
    }
325
  }
326
327
268
  return scope.EscapeMaybe(New(isolate, data, actual));
328
}
329
330
331
1
MaybeLocal<Object> New(Isolate* isolate, size_t length) {
332
1
  EscapableHandleScope handle_scope(isolate);
333
  Local<Object> obj;
334
1
  Environment* env = Environment::GetCurrent(isolate);
335
1
  if (env == nullptr) {
336
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
337
    return MaybeLocal<Object>();
338
  }
339
2
  if (Buffer::New(env, length).ToLocal(&obj))
340
1
    return handle_scope.Escape(obj);
341
  return Local<Object>();
342
}
343
344
345
1350
MaybeLocal<Object> New(Environment* env, size_t length) {
346
1350
  EscapableHandleScope scope(env->isolate());
347
348
  // V8 currently only allows a maximum Typed Array index of max Smi.
349
1350
  if (length > kMaxLength) {
350
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
351
    return Local<Object>();
352
  }
353
354
  return scope.EscapeMaybe(
355
2700
      AllocatedBuffer::AllocateManaged(env, length).ToBuffer());
356
}
357
358
359
3121
MaybeLocal<Object> Copy(Isolate* isolate, const char* data, size_t length) {
360
3121
  EscapableHandleScope handle_scope(isolate);
361
3121
  Environment* env = Environment::GetCurrent(isolate);
362
3121
  if (env == nullptr) {
363
1
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
364
1
    return MaybeLocal<Object>();
365
  }
366
  Local<Object> obj;
367
6240
  if (Buffer::Copy(env, data, length).ToLocal(&obj))
368
3120
    return handle_scope.Escape(obj);
369
  return Local<Object>();
370
}
371
372
373
7709
MaybeLocal<Object> Copy(Environment* env, const char* data, size_t length) {
374
7709
  EscapableHandleScope scope(env->isolate());
375
376
  // V8 currently only allows a maximum Typed Array index of max Smi.
377
7709
  if (length > kMaxLength) {
378
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
379
    return Local<Object>();
380
  }
381
382
15418
  AllocatedBuffer ret = AllocatedBuffer::AllocateManaged(env, length);
383
7709
  if (length > 0) {
384
7558
    memcpy(ret.data(), data, length);
385
  }
386
387
7709
  return scope.EscapeMaybe(ret.ToBuffer());
388
}
389
390
391
29
MaybeLocal<Object> New(Isolate* isolate,
392
                       char* data,
393
                       size_t length,
394
                       FreeCallback callback,
395
                       void* hint) {
396
29
  EscapableHandleScope handle_scope(isolate);
397
29
  Environment* env = Environment::GetCurrent(isolate);
398
29
  if (env == nullptr) {
399
    callback(data, hint);
400
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
401
    return MaybeLocal<Object>();
402
  }
403
  return handle_scope.EscapeMaybe(
404
58
      Buffer::New(env, data, length, callback, hint));
405
}
406
407
408
531
MaybeLocal<Object> New(Environment* env,
409
                       char* data,
410
                       size_t length,
411
                       FreeCallback callback,
412
                       void* hint) {
413
531
  EscapableHandleScope scope(env->isolate());
414
415
531
  if (length > kMaxLength) {
416
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
417
    callback(data, hint);
418
    return Local<Object>();
419
  }
420
421
  Local<ArrayBuffer> ab =
422
531
      CallbackInfo::CreateTrackedArrayBuffer(env, data, length, callback, hint);
423
1593
  if (ab->SetPrivate(env->context(),
424
                     env->untransferable_object_private_symbol(),
425
1593
                     True(env->isolate())).IsNothing()) {
426
    return Local<Object>();
427
  }
428
531
  MaybeLocal<Uint8Array> maybe_ui = Buffer::New(env, ab, 0, length);
429
430
  Local<Uint8Array> ui;
431
531
  if (!maybe_ui.ToLocal(&ui))
432
    return MaybeLocal<Object>();
433
434
531
  return scope.Escape(ui);
435
}
436
437
// Warning: This function needs `data` to be allocated with malloc() and not
438
// necessarily isolate's ArrayBuffer::Allocator.
439
134
MaybeLocal<Object> New(Isolate* isolate, char* data, size_t length) {
440
134
  EscapableHandleScope handle_scope(isolate);
441
134
  Environment* env = Environment::GetCurrent(isolate);
442
134
  if (env == nullptr) {
443
    free(data);
444
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
445
    return MaybeLocal<Object>();
446
  }
447
  Local<Object> obj;
448
268
  if (Buffer::New(env, data, length).ToLocal(&obj))
449
134
    return handle_scope.Escape(obj);
450
  return Local<Object>();
451
}
452
453
// The contract for this function is that `data` is allocated with malloc()
454
// and not necessarily isolate's ArrayBuffer::Allocator.
455
502
MaybeLocal<Object> New(Environment* env,
456
                       char* data,
457
                       size_t length) {
458
502
  if (length > 0) {
459
500
    CHECK_NOT_NULL(data);
460
500
    CHECK(length <= kMaxLength);
461
  }
462
463
1480
  auto free_callback = [](char* data, void* hint) { free(data); };
464
502
  return New(env, data, length, free_callback, nullptr);
465
}
466
467
namespace {
468
469
134
void CreateFromString(const FunctionCallbackInfo<Value>& args) {
470
402
  CHECK(args[0]->IsString());
471
268
  CHECK(args[1]->IsInt32());
472
473
402
  enum encoding enc = static_cast<enum encoding>(args[1].As<Int32>()->Value());
474
  Local<Object> buf;
475
402
  if (New(args.GetIsolate(), args[0].As<String>(), enc).ToLocal(&buf))
476
268
    args.GetReturnValue().Set(buf);
477
134
}
478
479
480
template <encoding encoding>
481
123389
void StringSlice(const FunctionCallbackInfo<Value>& args) {
482
123389
  Environment* env = Environment::GetCurrent(args);
483
123389
  Isolate* isolate = env->isolate();
484
485



123579
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
486
123389
  ArrayBufferViewContents<char> buffer(args.This());
487
488



123389
  if (buffer.length() == 0)
489
366
    return args.GetReturnValue().SetEmptyString();
490
491
123206
  size_t start = 0;
492
123206
  size_t end = 0;
493







492824
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[0], 0, &start));
494







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



123206
  if (end < start) end = start;
496







369618
  THROW_AND_RETURN_IF_OOB(Just(end <= buffer.length()));
497
123206
  size_t length = end - start;
498
499
  Local<Value> error;
500
  MaybeLocal<Value> maybe_ret =
501
123206
      StringBytes::Encode(isolate,
502
123206
                          buffer.data() + start,
503
                          length,
504
                          encoding,
505
123206
                          &error);
506
  Local<Value> ret;
507



123206
  if (!maybe_ret.ToLocal(&ret)) {
508



7
    CHECK(!error.IsEmpty());
509
7
    isolate->ThrowException(error);
510
7
    return;
511
  }
512
246398
  args.GetReturnValue().Set(ret);
513
}
514
515
516
// bytesCopied = copy(buffer, target[, targetStart][, sourceStart][, sourceEnd])
517
13
void Copy(const FunctionCallbackInfo<Value> &args) {
518
13
  Environment* env = Environment::GetCurrent(args);
519
520
13
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
521
13
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
522
13
  ArrayBufferViewContents<char> source(args[0]);
523
26
  Local<Object> target_obj = args[1].As<Object>();
524
78
  SPREAD_BUFFER_ARG(target_obj, target);
525
526
13
  size_t target_start = 0;
527
13
  size_t source_start = 0;
528
26
  size_t source_end = 0;
529
13
530

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

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

65
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], source.length(),
533
                                          &source_end));
534
535
  // Copy 0 bytes; we're done
536

13
  if (target_start >= target_length || source_start >= source_end)
537
    return args.GetReturnValue().Set(0);
538
539
13
  if (source_start > source.length())
540
    return THROW_ERR_OUT_OF_RANGE(
541
        env, "The value of \"sourceStart\" is out of range.");
542
543
13
  if (source_end - source_start > target_length - target_start)
544
    source_end = source_start + target_length - target_start;
545
546
13
  uint32_t to_copy = std::min(
547
26
      std::min(source_end - source_start, target_length - target_start),
548
52
      source.length() - source_start);
549
550
13
  memmove(target_data + target_start, source.data() + source_start, to_copy);
551
26
  args.GetReturnValue().Set(to_copy);
552
}
553
554
555
177
void Fill(const FunctionCallbackInfo<Value>& args) {
556
177
  Environment* env = Environment::GetCurrent(args);
557
177
  Local<Context> ctx = env->context();
558
559
198
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
560
354
  SPREAD_BUFFER_ARG(args[0], ts_obj);
561
562
354
  size_t start;
563

1395
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &start));
564

354
  size_t end;
565

881
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &end));
566
567
175
  size_t fill_length = end - start;
568
  Local<String> str_obj;
569
  size_t str_length;
570
  enum encoding enc;
571
572
  // OOB Check. Throw the error in JS.
573

175
  if (start > end || fill_length + start > ts_obj_length)
574
    return args.GetReturnValue().Set(-2);
575
576
  // First check if Buffer has been passed.
577
175
  if (Buffer::HasInstance(args[1])) {
578
14
    SPREAD_BUFFER_ARG(args[1], fill_obj);
579
7
    str_length = fill_obj_length;
580
28
    memcpy(
581
49
        ts_obj_data + start, fill_obj_data, std::min(str_length, fill_length));
582
14
    goto start_fill;
583
6
  }
584
585
  // Then coerce everything that's not a string.
586
504
  if (!args[1]->IsString()) {
587
    uint32_t val;
588
9
    if (!args[1]->Uint32Value(ctx).To(&val)) return;
589
3
    int value = val & 255;
590
3
    memset(ts_obj_data + start, value, fill_length);
591
3
    return;
592
  }
593
594
660
  str_obj = args[1]->ToString(env->context()).ToLocalChecked();
595
165
  enc = ParseEncoding(env->isolate(), args[4], UTF8);
596
597
  // Can't use StringBytes::Write() in all cases. For example if attempting
598
  // to write a two byte character into a one byte Buffer.
599
165
  if (enc == UTF8) {
600
98
    str_length = str_obj->Utf8Length(env->isolate());
601
98
    node::Utf8Value str(env->isolate(), args[1]);
602
49
    memcpy(ts_obj_data + start, *str, std::min(str_length, fill_length));
603
604
116
  } else if (enc == UCS2) {
605
23
    str_length = str_obj->Length() * sizeof(uint16_t);
606
46
    node::TwoByteValue str(env->isolate(), args[1]);
607
23
    if (IsBigEndian())
608
      SwapBytes16(reinterpret_cast<char*>(&str[0]), str_length);
609
610
23
    memcpy(ts_obj_data + start, *str, std::min(str_length, fill_length));
611
612
  } else {
613
    // Write initial String to Buffer, then use that memory to copy remainder
614
    // of string. Correct the string length for cases like HEX where less than
615
    // the total string length is written.
616
186
    str_length = StringBytes::Write(env->isolate(),
617
93
                                    ts_obj_data + start,
618
                                    fill_length,
619
                                    str_obj,
620
                                    enc,
621
                                    nullptr);
622
  }
623
624
start_fill:
625
626
172
  if (str_length >= fill_length)
627
10
    return;
628
629
  // If str_length is zero, then either an empty buffer was provided, or Write()
630
  // indicated that no bytes could be written. If no bytes could be written,
631
  // then return -1 because the fill value is invalid. This will trigger a throw
632
  // in JavaScript. Silently failing should be avoided because it can lead to
633
  // buffers with unexpected contents.
634
162
  if (str_length == 0)
635
12
    return args.GetReturnValue().Set(-1);
636
637
156
  size_t in_there = str_length;
638
156
  char* ptr = ts_obj_data + start + str_length;
639
640
734
  while (in_there < fill_length - in_there) {
641
289
    memcpy(ptr, ts_obj_data + start, in_there);
642
289
    ptr += in_there;
643
289
    in_there *= 2;
644
  }
645
646
156
  if (in_there < fill_length) {
647
156
    memcpy(ptr, ts_obj_data + start, fill_length - in_there);
648
  }
649
}
650
651
652
template <encoding encoding>
653
153380
void StringWrite(const FunctionCallbackInfo<Value>& args) {
654
153380
  Environment* env = Environment::GetCurrent(args);
655
656



153385
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
657



306760
  SPREAD_BUFFER_ARG(args.This(), ts_obj);
658
659



766900
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "argument");
660
613515
661



766900
  Local<String> str = args[0]->ToString(env->context()).ToLocalChecked();
662



153376
663
  size_t offset;
664
  size_t max_length;
665
666







613520
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], 0, &offset));
667



153380
  if (offset > ts_obj_length) {
668
    return node::THROW_ERR_BUFFER_OUT_OF_BOUNDS(
669
        env, "\"offset\" is outside of buffer bounds");
670
  }
671
672







766900
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], ts_obj_length - offset,
673
                                          &max_length));
674
675
153380
  max_length = std::min(ts_obj_length - offset, max_length);
676
677



153380
  if (max_length == 0)
678
10
    return args.GetReturnValue().Set(0);
679
680
460125
  uint32_t written = StringBytes::Write(env->isolate(),
681
153375
                                        ts_obj_data + offset,
682
                                        max_length,
683
                                        str,
684
                                        encoding,
685
153375
                                        nullptr);
686



306750
  args.GetReturnValue().Set(written);
687
}
688
689
135202
void ByteLengthUtf8(const FunctionCallbackInfo<Value> &args) {
690
135202
  Environment* env = Environment::GetCurrent(args);
691
405606
  CHECK(args[0]->IsString());
692
693
  // Fast case: avoid StringBytes on UTF8 string. Jump to v8.
694
811212
  args.GetReturnValue().Set(args[0].As<String>()->Utf8Length(env->isolate()));
695
135202
}
696
697
// Normalize val to be an integer in the range of [1, -1] since
698
// implementations of memcmp() can vary by platform.
699
3541
static int normalizeCompareVal(int val, size_t a_length, size_t b_length) {
700
3541
  if (val == 0) {
701
3514
    if (a_length > b_length)
702
6
      return 1;
703
3508
    else if (a_length < b_length)
704
5
      return -1;
705
  } else {
706
27
    if (val > 0)
707
7
      return 1;
708
    else
709
20
      return -1;
710
  }
711
3503
  return val;
712
}
713
714
9
void CompareOffset(const FunctionCallbackInfo<Value> &args) {
715
9
  Environment* env = Environment::GetCurrent(args);
716
717
9
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
718
9
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
719
9
  ArrayBufferViewContents<char> source(args[0]);
720
9
  ArrayBufferViewContents<char> target(args[1]);
721
722
9
  size_t target_start = 0;
723
9
  size_t source_start = 0;
724
9
  size_t source_end = 0;
725
9
  size_t target_end = 0;
726
727

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

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

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

45
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[5], source.length(),
732
                                          &source_end));
733
734
9
  if (source_start > source.length())
735
    return THROW_ERR_OUT_OF_RANGE(
736
        env, "The value of \"sourceStart\" is out of range.");
737
9
  if (target_start > target.length())
738
    return THROW_ERR_OUT_OF_RANGE(
739
        env, "The value of \"targetStart\" is out of range.");
740
741
9
  CHECK_LE(source_start, source_end);
742
9
  CHECK_LE(target_start, target_end);
743
744
  size_t to_cmp =
745
18
      std::min(std::min(source_end - source_start, target_end - target_start),
746
27
               source.length() - source_start);
747
748
18
  int val = normalizeCompareVal(to_cmp > 0 ?
749
9
                                  memcmp(source.data() + source_start,
750
9
                                         target.data() + target_start,
751
                                         to_cmp) : 0,
752
                                source_end - source_start,
753
9
                                target_end - target_start);
754
755
18
  args.GetReturnValue().Set(val);
756
}
757
758
3532
void Compare(const FunctionCallbackInfo<Value> &args) {
759
3532
  Environment* env = Environment::GetCurrent(args);
760
761
3532
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
762
3532
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
763
3532
  ArrayBufferViewContents<char> a(args[0]);
764
3532
  ArrayBufferViewContents<char> b(args[1]);
765
766
3532
  size_t cmp_length = std::min(a.length(), b.length());
767
768
7000
  int val = normalizeCompareVal(cmp_length > 0 ?
769
3468
                                memcmp(a.data(), b.data(), cmp_length) : 0,
770
3532
                                a.length(), b.length());
771
7064
  args.GetReturnValue().Set(val);
772
}
773
774
775
// Computes the offset for starting an indexOf or lastIndexOf search.
776
// Returns either a valid offset in [0...<length - 1>], ie inside the Buffer,
777
// or -1 to signal that there is no possible match.
778
1158
int64_t IndexOfOffset(size_t length,
779
                      int64_t offset_i64,
780
                      int64_t needle_length,
781
                      bool is_forward) {
782
1158
  int64_t length_i64 = static_cast<int64_t>(length);
783
1158
  if (offset_i64 < 0) {
784
77
    if (offset_i64 + length_i64 >= 0) {
785
      // Negative offsets count backwards from the end of the buffer.
786
59
      return length_i64 + offset_i64;
787

18
    } else if (is_forward || needle_length == 0) {
788
      // indexOf from before the start of the buffer: search the whole buffer.
789
10
      return 0;
790
    } else {
791
      // lastIndexOf from before the start of the buffer: no match.
792
8
      return -1;
793
    }
794
  } else {
795
1081
    if (offset_i64 + needle_length <= length_i64) {
796
      // Valid positive offset.
797
993
      return offset_i64;
798
88
    } else if (needle_length == 0) {
799
      // Out of buffer bounds, but empty needle: point to end of buffer.
800
10
      return length_i64;
801
78
    } else if (is_forward) {
802
      // indexOf from past the end of the buffer: no match.
803
15
      return -1;
804
    } else {
805
      // lastIndexOf from past the end of the buffer: search the whole buffer.
806
63
      return length_i64 - 1;
807
    }
808
  }
809
}
810
811
890
void IndexOfString(const FunctionCallbackInfo<Value>& args) {
812
890
  Environment* env = Environment::GetCurrent(args);
813
890
  Isolate* isolate = env->isolate();
814
815
2670
  CHECK(args[1]->IsString());
816
1780
  CHECK(args[2]->IsNumber());
817
1780
  CHECK(args[3]->IsInt32());
818
1780
  CHECK(args[4]->IsBoolean());
819
820
2670
  enum encoding enc = static_cast<enum encoding>(args[3].As<Int32>()->Value());
821
822
923
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
823
890
  ArrayBufferViewContents<char> buffer(args[0]);
824
825
1780
  Local<String> needle = args[1].As<String>();
826
2670
  int64_t offset_i64 = args[2].As<Integer>()->Value();
827
1780
  bool is_forward = args[4]->IsTrue();
828
829
890
  const char* haystack = buffer.data();
830
  // Round down to the nearest multiple of 2 in case of UCS2.
831
980
  const size_t haystack_length = (enc == UCS2) ?
832
980
      buffer.length() &~ 1 : buffer.length();  // NOLINT(whitespace/operators)
833
834
  size_t needle_length;
835
1780
  if (!StringBytes::Size(isolate, needle, enc).To(&needle_length)) return;
836
837
890
  int64_t opt_offset = IndexOfOffset(haystack_length,
838
                                     offset_i64,
839
                                     needle_length,
840
890
                                     is_forward);
841
842
890
  if (needle_length == 0) {
843
    // Match String#indexOf() and String#lastIndexOf() behavior.
844
24
    args.GetReturnValue().Set(static_cast<double>(opt_offset));
845
8
    return;
846
  }
847
848
882
  if (haystack_length == 0) {
849
    return args.GetReturnValue().Set(-1);
850
  }
851
852
882
  if (opt_offset <= -1) {
853
20
    return args.GetReturnValue().Set(-1);
854
  }
855
872
  size_t offset = static_cast<size_t>(opt_offset);
856
872
  CHECK_LT(offset, haystack_length);
857

1742
  if ((is_forward && needle_length + offset > haystack_length) ||
858
870
      needle_length > haystack_length) {
859
30
    return args.GetReturnValue().Set(-1);
860
  }
861
862
857
  size_t result = haystack_length;
863
864
857
  if (enc == UCS2) {
865
170
    String::Value needle_value(isolate, needle);
866
85
    if (*needle_value == nullptr)
867
      return args.GetReturnValue().Set(-1);
868
869

85
    if (haystack_length < 2 || needle_value.length() < 1) {
870
      return args.GetReturnValue().Set(-1);
871
    }
872
873
85
    if (IsBigEndian()) {
874
      StringBytes::InlineDecoder decoder;
875
      if (decoder.Decode(env, needle, enc).IsNothing()) return;
876
      const uint16_t* decoded_string =
877
          reinterpret_cast<const uint16_t*>(decoder.out());
878
879
      if (decoded_string == nullptr)
880
        return args.GetReturnValue().Set(-1);
881
882
      result = SearchString(reinterpret_cast<const uint16_t*>(haystack),
883
                            haystack_length / 2,
884
                            decoded_string,
885
                            decoder.size() / 2,
886
                            offset / 2,
887
                            is_forward);
888
    } else {
889
255
      result = SearchString(reinterpret_cast<const uint16_t*>(haystack),
890
                            haystack_length / 2,
891
85
                            reinterpret_cast<const uint16_t*>(*needle_value),
892
85
                            needle_value.length(),
893
                            offset / 2,
894
85
                            is_forward);
895
    }
896
85
    result *= 2;
897
772
  } else if (enc == UTF8) {
898
1520
    String::Utf8Value needle_value(isolate, needle);
899
760
    if (*needle_value == nullptr)
900
      return args.GetReturnValue().Set(-1);
901
902
1520
    result = SearchString(reinterpret_cast<const uint8_t*>(haystack),
903
                          haystack_length,
904
760
                          reinterpret_cast<const uint8_t*>(*needle_value),
905
                          needle_length,
906
                          offset,
907
760
                          is_forward);
908
12
  } else if (enc == LATIN1) {
909
12
    uint8_t* needle_data = node::UncheckedMalloc<uint8_t>(needle_length);
910
12
    if (needle_data == nullptr) {
911
      return args.GetReturnValue().Set(-1);
912
    }
913
24
    needle->WriteOneByte(
914
12
        isolate, needle_data, 0, needle_length, String::NO_NULL_TERMINATION);
915
916
12
    result = SearchString(reinterpret_cast<const uint8_t*>(haystack),
917
                          haystack_length,
918
                          needle_data,
919
                          needle_length,
920
                          offset,
921
12
                          is_forward);
922
12
    free(needle_data);
923
  }
924
925
2571
  args.GetReturnValue().Set(
926
857
      result == haystack_length ? -1 : static_cast<int>(result));
927
}
928
929
218
void IndexOfBuffer(const FunctionCallbackInfo<Value>& args) {
930
436
  CHECK(args[1]->IsObject());
931
436
  CHECK(args[2]->IsNumber());
932
436
  CHECK(args[3]->IsInt32());
933
436
  CHECK(args[4]->IsBoolean());
934
935
654
  enum encoding enc = static_cast<enum encoding>(args[3].As<Int32>()->Value());
936
937
248
  THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[0]);
938
218
  THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[1]);
939
218
  ArrayBufferViewContents<char> haystack_contents(args[0]);
940
218
  ArrayBufferViewContents<char> needle_contents(args[1]);
941
654
  int64_t offset_i64 = args[2].As<Integer>()->Value();
942
436
  bool is_forward = args[4]->IsTrue();
943
944
218
  const char* haystack = haystack_contents.data();
945
218
  const size_t haystack_length = haystack_contents.length();
946
218
  const char* needle = needle_contents.data();
947
218
  const size_t needle_length = needle_contents.length();
948
949
218
  int64_t opt_offset = IndexOfOffset(haystack_length,
950
                                     offset_i64,
951
                                     needle_length,
952
218
                                     is_forward);
953
954
218
  if (needle_length == 0) {
955
    // Match String#indexOf() and String#lastIndexOf() behavior.
956
36
    args.GetReturnValue().Set(static_cast<double>(opt_offset));
957
12
    return;
958
  }
959
960
206
  if (haystack_length == 0) {
961
    return args.GetReturnValue().Set(-1);
962
  }
963
964
206
  if (opt_offset <= -1) {
965
18
    return args.GetReturnValue().Set(-1);
966
  }
967
197
  size_t offset = static_cast<size_t>(opt_offset);
968
197
  CHECK_LT(offset, haystack_length);
969

392
  if ((is_forward && needle_length + offset > haystack_length) ||
970
195
      needle_length > haystack_length) {
971
14
    return args.GetReturnValue().Set(-1);
972
  }
973
974
190
  size_t result = haystack_length;
975
976
190
  if (enc == UCS2) {
977

58
    if (haystack_length < 2 || needle_length < 2) {
978
4
      return args.GetReturnValue().Set(-1);
979
    }
980
56
    result = SearchString(
981
        reinterpret_cast<const uint16_t*>(haystack),
982
        haystack_length / 2,
983
        reinterpret_cast<const uint16_t*>(needle),
984
        needle_length / 2,
985
        offset / 2,
986
56
        is_forward);
987
56
    result *= 2;
988
  } else {
989
132
    result = SearchString(
990
        reinterpret_cast<const uint8_t*>(haystack),
991
        haystack_length,
992
        reinterpret_cast<const uint8_t*>(needle),
993
        needle_length,
994
        offset,
995
132
        is_forward);
996
  }
997
998
564
  args.GetReturnValue().Set(
999
188
      result == haystack_length ? -1 : static_cast<int>(result));
1000
}
1001
1002
50
void IndexOfNumber(const FunctionCallbackInfo<Value>& args) {
1003
100
  CHECK(args[1]->IsUint32());
1004
100
  CHECK(args[2]->IsNumber());
1005
100
  CHECK(args[3]->IsBoolean());
1006
1007
54
  THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[0]);
1008
50
  ArrayBufferViewContents<char> buffer(args[0]);
1009
1010
150
  uint32_t needle = args[1].As<Uint32>()->Value();
1011
150
  int64_t offset_i64 = args[2].As<Integer>()->Value();
1012
100
  bool is_forward = args[3]->IsTrue();
1013
1014
  int64_t opt_offset =
1015
50
      IndexOfOffset(buffer.length(), offset_i64, 1, is_forward);
1016

50
  if (opt_offset <= -1 || buffer.length() == 0) {
1017
8
    return args.GetReturnValue().Set(-1);
1018
  }
1019
46
  size_t offset = static_cast<size_t>(opt_offset);
1020
46
  CHECK_LT(offset, buffer.length());
1021
1022
  const void* ptr;
1023
46
  if (is_forward) {
1024
38
    ptr = memchr(buffer.data() + offset, needle, buffer.length() - offset);
1025
  } else {
1026
8
    ptr = node::stringsearch::MemrchrFill(buffer.data(), needle, offset + 1);
1027
  }
1028
46
  const char* ptr_char = static_cast<const char*>(ptr);
1029
138
  args.GetReturnValue().Set(ptr ? static_cast<int>(ptr_char - buffer.data())
1030
                                : -1);
1031
}
1032
1033
1034
2
void Swap16(const FunctionCallbackInfo<Value>& args) {
1035
2
  Environment* env = Environment::GetCurrent(args);
1036
2
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1037
16
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1038
2
  SwapBytes16(ts_obj_data, ts_obj_length);
1039
4
  args.GetReturnValue().Set(args[0]);
1040
}
1041

4
1042
2
1043
2
void Swap32(const FunctionCallbackInfo<Value>& args) {
1044
2
  Environment* env = Environment::GetCurrent(args);
1045
2
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1046
4
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1047
2
  SwapBytes32(ts_obj_data, ts_obj_length);
1048
8
  args.GetReturnValue().Set(args[0]);
1049
8
}
1050

4
1051
2
1052
2
void Swap64(const FunctionCallbackInfo<Value>& args) {
1053
2
  Environment* env = Environment::GetCurrent(args);
1054
2
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1055
4
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1056
2
  SwapBytes64(ts_obj_data, ts_obj_length);
1057
8
  args.GetReturnValue().Set(args[0]);
1058
8
}
1059

4
1060
2
1061
// Encode a single string to a UTF-8 Uint8Array (not Buffer).
1062
// Used in TextEncoder.prototype.encode.
1063
128
static void EncodeUtf8String(const FunctionCallbackInfo<Value>& args) {
1064
128
  Environment* env = Environment::GetCurrent(args);
1065
128
  Isolate* isolate = env->isolate();
1066
128
  CHECK_GE(args.Length(), 1);
1067
384
  CHECK(args[0]->IsString());
1068
1069
256
  Local<String> str = args[0].As<String>();
1070
128
  size_t length = str->Utf8Length(isolate);
1071
256
  AllocatedBuffer buf = AllocatedBuffer::AllocateManaged(env, length);
1072
256
  str->WriteUtf8(isolate,
1073
                 buf.data(),
1074
                 -1,  // We are certain that `data` is sufficiently large
1075
                 nullptr,
1076
128
                 String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8);
1077
128
  auto array = Uint8Array::New(buf.ToArrayBuffer(), 0, length);
1078
256
  args.GetReturnValue().Set(array);
1079
128
}
1080
1081
1082
45
static void EncodeInto(const FunctionCallbackInfo<Value>& args) {
1083
45
  Environment* env = Environment::GetCurrent(args);
1084
45
  Isolate* isolate = env->isolate();
1085
45
  CHECK_GE(args.Length(), 3);
1086
135
  CHECK(args[0]->IsString());
1087
90
  CHECK(args[1]->IsUint8Array());
1088
90
  CHECK(args[2]->IsUint32Array());
1089
1090
90
  Local<String> source = args[0].As<String>();
1091
1092
90
  Local<Uint8Array> dest = args[1].As<Uint8Array>();
1093
45
  Local<ArrayBuffer> buf = dest->Buffer();
1094
  char* write_result =
1095
90
      static_cast<char*>(buf->GetBackingStore()->Data()) + dest->ByteOffset();
1096
45
  size_t dest_length = dest->ByteLength();
1097
1098
  // results = [ read, written ]
1099
90
  Local<Uint32Array> result_arr = args[2].As<Uint32Array>();
1100
  uint32_t* results = reinterpret_cast<uint32_t*>(
1101
135
      static_cast<char*>(result_arr->Buffer()->GetBackingStore()->Data()) +
1102
45
      result_arr->ByteOffset());
1103
1104
  int nchars;
1105
90
  int written = source->WriteUtf8(
1106
      isolate,
1107
      write_result,
1108
      dest_length,
1109
      &nchars,
1110
45
      String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8);
1111
45
  results[0] = nchars;
1112
45
  results[1] = written;
1113
45
}
1114
1115
1116
462
void SetBufferPrototype(const FunctionCallbackInfo<Value>& args) {
1117
462
  Environment* env = Environment::GetCurrent(args);
1118
1119
924
  CHECK(args[0]->IsObject());
1120
924
  Local<Object> proto = args[0].As<Object>();
1121
462
  env->set_buffer_prototype_object(proto);
1122
462
}
1123
1124
5178
void GetZeroFillToggle(const FunctionCallbackInfo<Value>& args) {
1125
5178
  Environment* env = Environment::GetCurrent(args);
1126
5178
  NodeArrayBufferAllocator* allocator = env->isolate_data()->node_allocator();
1127
  Local<ArrayBuffer> ab;
1128
  // It can be a nullptr when running inside an isolate where we
1129
  // do not own the ArrayBuffer allocator.
1130
5178
  if (allocator == nullptr) {
1131
    // Create a dummy Uint32Array - the JS land can only toggle the C++ land
1132
    // setting when the allocator uses our toggle. With this the toggle in JS
1133
    // land results in no-ops.
1134
59
    ab = ArrayBuffer::New(env->isolate(), sizeof(uint32_t));
1135
  } else {
1136
5119
    uint32_t* zero_fill_field = allocator->zero_fill_field();
1137
    std::unique_ptr<BackingStore> backing =
1138
        ArrayBuffer::NewBackingStore(zero_fill_field,
1139
                                     sizeof(*zero_fill_field),
1140
14269
                                     [](void*, size_t, void*) {},
1141
10238
                                     nullptr);
1142
5119
    ab = ArrayBuffer::New(env->isolate(), std::move(backing));
1143
  }
1144
1145
10356
  ab->SetPrivate(
1146
      env->context(),
1147
      env->untransferable_object_private_symbol(),
1148
15534
      True(env->isolate())).Check();
1149
1150
15534
  args.GetReturnValue().Set(Uint32Array::New(ab, 0, 1));
1151
5178
}
1152
1153
462
void Initialize(Local<Object> target,
1154
                Local<Value> unused,
1155
                Local<Context> context,
1156
                void* priv) {
1157
462
  Environment* env = Environment::GetCurrent(context);
1158
1159
462
  env->SetMethod(target, "setBufferPrototype", SetBufferPrototype);
1160
462
  env->SetMethodNoSideEffect(target, "createFromString", CreateFromString);
1161
1162
462
  env->SetMethodNoSideEffect(target, "byteLengthUtf8", ByteLengthUtf8);
1163
462
  env->SetMethod(target, "copy", Copy);
1164
462
  env->SetMethodNoSideEffect(target, "compare", Compare);
1165
462
  env->SetMethodNoSideEffect(target, "compareOffset", CompareOffset);
1166
462
  env->SetMethod(target, "fill", Fill);
1167
462
  env->SetMethodNoSideEffect(target, "indexOfBuffer", IndexOfBuffer);
1168
462
  env->SetMethodNoSideEffect(target, "indexOfNumber", IndexOfNumber);
1169
462
  env->SetMethodNoSideEffect(target, "indexOfString", IndexOfString);
1170
1171
462
  env->SetMethod(target, "swap16", Swap16);
1172
462
  env->SetMethod(target, "swap32", Swap32);
1173
462
  env->SetMethod(target, "swap64", Swap64);
1174
1175
462
  env->SetMethod(target, "encodeInto", EncodeInto);
1176
462
  env->SetMethodNoSideEffect(target, "encodeUtf8String", EncodeUtf8String);
1177
1178
924
  target->Set(env->context(),
1179
              FIXED_ONE_BYTE_STRING(env->isolate(), "kMaxLength"),
1180
2310
              Number::New(env->isolate(), kMaxLength)).Check();
1181
1182
924
  target->Set(env->context(),
1183
              FIXED_ONE_BYTE_STRING(env->isolate(), "kStringMaxLength"),
1184
2310
              Integer::New(env->isolate(), String::kMaxLength)).Check();
1185
1186
462
  env->SetMethodNoSideEffect(target, "asciiSlice", StringSlice<ASCII>);
1187
462
  env->SetMethodNoSideEffect(target, "base64Slice", StringSlice<BASE64>);
1188
462
  env->SetMethodNoSideEffect(target, "base64urlSlice", StringSlice<BASE64URL>);
1189
462
  env->SetMethodNoSideEffect(target, "latin1Slice", StringSlice<LATIN1>);
1190
462
  env->SetMethodNoSideEffect(target, "hexSlice", StringSlice<HEX>);
1191
462
  env->SetMethodNoSideEffect(target, "ucs2Slice", StringSlice<UCS2>);
1192
462
  env->SetMethodNoSideEffect(target, "utf8Slice", StringSlice<UTF8>);
1193
1194
462
  env->SetMethod(target, "asciiWrite", StringWrite<ASCII>);
1195
462
  env->SetMethod(target, "base64Write", StringWrite<BASE64>);
1196
462
  env->SetMethod(target, "base64urlWrite", StringWrite<BASE64URL>);
1197
462
  env->SetMethod(target, "latin1Write", StringWrite<LATIN1>);
1198
462
  env->SetMethod(target, "hexWrite", StringWrite<HEX>);
1199
462
  env->SetMethod(target, "ucs2Write", StringWrite<UCS2>);
1200
462
  env->SetMethod(target, "utf8Write", StringWrite<UTF8>);
1201
1202
462
  env->SetMethod(target, "getZeroFillToggle", GetZeroFillToggle);
1203
1204
462
  Blob::Initialize(env, target);
1205
462
}
1206
1207
}  // anonymous namespace
1208
1209
4703
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
1210
4703
  registry->Register(SetBufferPrototype);
1211
4703
  registry->Register(CreateFromString);
1212
1213
4703
  registry->Register(ByteLengthUtf8);
1214
4703
  registry->Register(Copy);
1215
4703
  registry->Register(Compare);
1216
4703
  registry->Register(CompareOffset);
1217
4703
  registry->Register(Fill);
1218
4703
  registry->Register(IndexOfBuffer);
1219
4703
  registry->Register(IndexOfNumber);
1220
4703
  registry->Register(IndexOfString);
1221
1222
4703
  registry->Register(Swap16);
1223
4703
  registry->Register(Swap32);
1224
4703
  registry->Register(Swap64);
1225
1226
4703
  registry->Register(EncodeInto);
1227
4703
  registry->Register(EncodeUtf8String);
1228
1229
4703
  registry->Register(StringSlice<ASCII>);
1230
4703
  registry->Register(StringSlice<BASE64>);
1231
4703
  registry->Register(StringSlice<BASE64URL>);
1232
4703
  registry->Register(StringSlice<LATIN1>);
1233
4703
  registry->Register(StringSlice<HEX>);
1234
4703
  registry->Register(StringSlice<UCS2>);
1235
4703
  registry->Register(StringSlice<UTF8>);
1236
1237
4703
  registry->Register(StringWrite<ASCII>);
1238
4703
  registry->Register(StringWrite<BASE64>);
1239
4703
  registry->Register(StringWrite<BASE64URL>);
1240
4703
  registry->Register(StringWrite<LATIN1>);
1241
4703
  registry->Register(StringWrite<HEX>);
1242
4703
  registry->Register(StringWrite<UCS2>);
1243
4703
  registry->Register(StringWrite<UTF8>);
1244
4703
  registry->Register(GetZeroFillToggle);
1245
1246
4703
  Blob::RegisterExternalReferences(registry);
1247
4703
  FixedSizeBlobCopyJob::RegisterExternalReferences(registry);
1248
4703
}
1249
1250
}  // namespace Buffer
1251
}  // namespace node
1252
1253
4762
NODE_MODULE_CONTEXT_AWARE_INTERNAL(buffer, node::Buffer::Initialize)
1254

19013
NODE_MODULE_EXTERNAL_REFERENCE(buffer, node::Buffer::RegisterExternalReferences)