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: 268 643 41.7 %
Date: 2021-02-19 04:08:54 Branches: 125 712 17.6 %

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
8
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
5
Local<ArrayBuffer> CallbackInfo::CreateTrackedArrayBuffer(
108
    Environment* env,
109
    char* data,
110
    size_t length,
111
    FreeCallback callback,
112
    void* hint) {
113
5
  CHECK_NOT_NULL(callback);
114

5
  CHECK_IMPLIES(data == nullptr, length == 0);
115
116
5
  CallbackInfo* self = new CallbackInfo(env, callback, data, hint);
117
  std::unique_ptr<BackingStore> bs =
118
13
      ArrayBuffer::NewBackingStore(data, length, [](void*, size_t, void* arg) {
119
4
        static_cast<CallbackInfo*>(arg)->OnBackingStoreFree();
120
23
      }, self);
121
5
  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
5
  if (data == nullptr) {
126
    ab->Detach();
127
    self->OnBackingStoreFree();  // This calls `callback` asynchronously.
128
  } else {
129
    // Store the ArrayBuffer so that we can detach it later.
130
5
    self->persistent_.Reset(env->isolate(), ab);
131
5
    self->persistent_.SetWeak();
132
  }
133
134
10
  return ab;
135
}
136
137
138
5
CallbackInfo::CallbackInfo(Environment* env,
139
                           FreeCallback callback,
140
                           char* data,
141
5
                           void* hint)
142
    : callback_(callback),
143
      data_(data),
144
      hint_(hint),
145
10
      env_(env) {
146
5
  env->AddCleanupHook(CleanupHook, this);
147
5
  env->isolate()->AdjustAmountOfExternalAllocatedMemory(sizeof(*this));
148
5
}
149
150
1
void CallbackInfo::CleanupHook(void* data) {
151
1
  CallbackInfo* self = static_cast<CallbackInfo*>(data);
152
153
  {
154
2
    HandleScope handle_scope(self->env_->isolate());
155
2
    Local<ArrayBuffer> ab = self->persistent_.Get(self->env_->isolate());
156

2
    if (!ab.IsEmpty() && ab->IsDetachable()) {
157
1
      ab->Detach();
158
1
      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
1
  self->CallAndResetCallback();
165
1
}
166
167
5
void CallbackInfo::CallAndResetCallback() {
168
  FreeCallback callback;
169
  {
170
10
    Mutex::ScopedLock lock(mutex_);
171
5
    callback = callback_;
172
5
    callback_ = nullptr;
173
  }
174
5
  if (callback != nullptr) {
175
    // Clean up all Environment-related state and run the callback.
176
4
    env_->RemoveCleanupHook(CleanupHook, this);
177
4
    int64_t change_in_bytes = -static_cast<int64_t>(sizeof(*this));
178
4
    env_->isolate()->AdjustAmountOfExternalAllocatedMemory(change_in_bytes);
179
180
4
    callback(data_, hint_);
181
  }
182
5
}
183
184
4
void CallbackInfo::OnBackingStoreFree() {
185
  // This method should always release the memory for `this`.
186
8
  std::unique_ptr<CallbackInfo> self { this };
187
8
  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
4
  if (callback_ == nullptr) return;
193
194
24
  env_->SetImmediateThreadsafe([self = std::move(self)](Environment* env) {
195
4
    CHECK_EQ(self->env_, env);  // Consistency check.
196
197
4
    self->CallAndResetCallback();
198
8
  });
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
310748
inline MUST_USE_RESULT Maybe<bool> ParseArrayIndex(Environment* env,
205
                                                   Local<Value> arg,
206
                                                   size_t def,
207
                                                   size_t* ret) {
208
621496
  if (arg->IsUndefined()) {
209
    *ret = def;
210
    return Just(true);
211
  }
212
213
  int64_t tmp_i;
214
932244
  if (!arg->IntegerValue(env->context()).To(&tmp_i))
215
    return Nothing<bool>();
216
217
310748
  if (tmp_i < 0)
218
    return Just(false);
219
220
  // Check that the result fits in a size_t.
221
310748
  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
310748
  *ret = static_cast<size_t>(tmp_i);
227
310748
  return Just(true);
228
}
229
230
}  // anonymous namespace
231
232
// Buffer methods
233
234
493772
bool HasInstance(Local<Value> val) {
235
493772
  return val->IsArrayBufferView();
236
}
237
238
239
77687
bool HasInstance(Local<Object> obj) {
240
77687
  return obj->IsArrayBufferView();
241
}
242
243
244
19322
char* Data(Local<Value> val) {
245
19322
  CHECK(val->IsArrayBufferView());
246
19322
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
247
57966
  return static_cast<char*>(ui->Buffer()->GetBackingStore()->Data()) +
248
38644
      ui->ByteOffset();
249
}
250
251
252
18546
char* Data(Local<Object> obj) {
253
18546
  return Data(obj.As<Value>());
254
}
255
256
257
2
size_t Length(Local<Value> val) {
258
2
  CHECK(val->IsArrayBufferView());
259
2
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
260
2
  return ui->ByteLength();
261
}
262
263
264
18532
size_t Length(Local<Object> obj) {
265
18532
  CHECK(obj->IsArrayBufferView());
266
18532
  Local<ArrayBufferView> ui = obj.As<ArrayBufferView>();
267
18532
  return ui->ByteLength();
268
}
269
270
271
37
MaybeLocal<Uint8Array> New(Environment* env,
272
                           Local<ArrayBuffer> ab,
273
                           size_t byte_offset,
274
                           size_t length) {
275
74
  CHECK(!env->buffer_prototype_object().IsEmpty());
276
37
  Local<Uint8Array> ui = Uint8Array::New(ab, byte_offset, length);
277
  Maybe<bool> mb =
278
111
      ui->SetPrototype(env->context(), env->buffer_prototype_object());
279
37
  if (mb.IsNothing())
280
    return MaybeLocal<Uint8Array>();
281
37
  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
4
MaybeLocal<Object> New(Isolate* isolate,
298
                       Local<String> string,
299
                       enum encoding enc) {
300
4
  EscapableHandleScope scope(isolate);
301
302
  size_t length;
303
8
  if (!StringBytes::Size(isolate, string, enc).To(&length))
304
    return Local<Object>();
305
4
  size_t actual = 0;
306
4
  char* data = nullptr;
307
308
4
  if (length > 0) {
309
4
    data = UncheckedMalloc(length);
310
311
4
    if (data == nullptr) {
312
      THROW_ERR_MEMORY_ALLOCATION_FAILED(isolate);
313
      return Local<Object>();
314
    }
315
316
4
    actual = StringBytes::Write(isolate, data, length, string, enc);
317
4
    CHECK(actual <= length);
318
319
4
    if (actual == 0) {
320
      free(data);
321
      data = nullptr;
322
4
    } else if (actual < length) {
323
      data = node::Realloc(data, actual);
324
    }
325
  }
326
327
8
  return scope.EscapeMaybe(New(isolate, data, actual));
328
}
329
330
331
MaybeLocal<Object> New(Isolate* isolate, size_t length) {
332
  EscapableHandleScope handle_scope(isolate);
333
  Local<Object> obj;
334
  Environment* env = Environment::GetCurrent(isolate);
335
  if (env == nullptr) {
336
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
337
    return MaybeLocal<Object>();
338
  }
339
  if (Buffer::New(env, length).ToLocal(&obj))
340
    return handle_scope.Escape(obj);
341
  return Local<Object>();
342
}
343
344
345
14
MaybeLocal<Object> New(Environment* env, size_t length) {
346
14
  EscapableHandleScope scope(env->isolate());
347
348
  // V8 currently only allows a maximum Typed Array index of max Smi.
349
14
  if (length > kMaxLength) {
350
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
351
    return Local<Object>();
352
  }
353
354
  return scope.EscapeMaybe(
355
28
      AllocatedBuffer::AllocateManaged(env, length).ToBuffer());
356
}
357
358
359
MaybeLocal<Object> Copy(Isolate* isolate, const char* data, size_t length) {
360
  EscapableHandleScope handle_scope(isolate);
361
  Environment* env = Environment::GetCurrent(isolate);
362
  if (env == nullptr) {
363
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
364
    return MaybeLocal<Object>();
365
  }
366
  Local<Object> obj;
367
  if (Buffer::Copy(env, data, length).ToLocal(&obj))
368
    return handle_scope.Escape(obj);
369
  return Local<Object>();
370
}
371
372
373
2
MaybeLocal<Object> Copy(Environment* env, const char* data, size_t length) {
374
2
  EscapableHandleScope scope(env->isolate());
375
376
  // V8 currently only allows a maximum Typed Array index of max Smi.
377
2
  if (length > kMaxLength) {
378
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
379
    return Local<Object>();
380
  }
381
382
4
  AllocatedBuffer ret = AllocatedBuffer::AllocateManaged(env, length);
383
2
  if (length > 0) {
384
2
    memcpy(ret.data(), data, length);
385
  }
386
387
2
  return scope.EscapeMaybe(ret.ToBuffer());
388
}
389
390
391
1
MaybeLocal<Object> New(Isolate* isolate,
392
                       char* data,
393
                       size_t length,
394
                       FreeCallback callback,
395
                       void* hint) {
396
1
  EscapableHandleScope handle_scope(isolate);
397
1
  Environment* env = Environment::GetCurrent(isolate);
398
1
  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
2
      Buffer::New(env, data, length, callback, hint));
405
}
406
407
408
5
MaybeLocal<Object> New(Environment* env,
409
                       char* data,
410
                       size_t length,
411
                       FreeCallback callback,
412
                       void* hint) {
413
5
  EscapableHandleScope scope(env->isolate());
414
415
5
  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
5
      CallbackInfo::CreateTrackedArrayBuffer(env, data, length, callback, hint);
423
15
  if (ab->SetPrivate(env->context(),
424
                     env->untransferable_object_private_symbol(),
425
15
                     True(env->isolate())).IsNothing()) {
426
    return Local<Object>();
427
  }
428
5
  MaybeLocal<Uint8Array> maybe_ui = Buffer::New(env, ab, 0, length);
429
430
  Local<Uint8Array> ui;
431
5
  if (!maybe_ui.ToLocal(&ui))
432
    return MaybeLocal<Object>();
433
434
5
  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
4
MaybeLocal<Object> New(Isolate* isolate, char* data, size_t length) {
440
4
  EscapableHandleScope handle_scope(isolate);
441
4
  Environment* env = Environment::GetCurrent(isolate);
442
4
  if (env == nullptr) {
443
    free(data);
444
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
445
    return MaybeLocal<Object>();
446
  }
447
  Local<Object> obj;
448
8
  if (Buffer::New(env, data, length).ToLocal(&obj))
449
4
    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
4
MaybeLocal<Object> New(Environment* env,
456
                       char* data,
457
                       size_t length) {
458
4
  if (length > 0) {
459
4
    CHECK_NOT_NULL(data);
460
4
    CHECK(length <= kMaxLength);
461
  }
462
463
10
  auto free_callback = [](char* data, void* hint) { free(data); };
464
4
  return New(env, data, length, free_callback, nullptr);
465
}
466
467
namespace {
468
469
4
void CreateFromString(const FunctionCallbackInfo<Value>& args) {
470
12
  CHECK(args[0]->IsString());
471
8
  CHECK(args[1]->IsInt32());
472
473
12
  enum encoding enc = static_cast<enum encoding>(args[1].As<Int32>()->Value());
474
  Local<Object> buf;
475
12
  if (New(args.GetIsolate(), args[0].As<String>(), enc).ToLocal(&buf))
476
8
    args.GetReturnValue().Set(buf);
477
4
}
478
479
480
template <encoding encoding>
481
63166
void StringSlice(const FunctionCallbackInfo<Value>& args) {
482
63166
  Environment* env = Environment::GetCurrent(args);
483
63166
  Isolate* isolate = env->isolate();
484
485



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



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







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







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



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







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



63166
  if (!maybe_ret.ToLocal(&ret)) {
508
    CHECK(!error.IsEmpty());
509
    isolate->ThrowException(error);
510
    return;
511
  }
512
126332
  args.GetReturnValue().Set(ret);
513
}
514
515
516
// bytesCopied = copy(buffer, target[, targetStart][, sourceStart][, sourceEnd])
517
void Copy(const FunctionCallbackInfo<Value> &args) {
518
  Environment* env = Environment::GetCurrent(args);
519
520
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
521
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
522
  ArrayBufferViewContents<char> source(args[0]);
523
  Local<Object> target_obj = args[1].As<Object>();
524
  SPREAD_BUFFER_ARG(target_obj, target);
525
526
  size_t target_start = 0;
527
  size_t source_start = 0;
528
  size_t source_end = 0;
529
530
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &target_start));
531
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &source_start));
532
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], source.length(),
533
                                          &source_end));
534
535
  // Copy 0 bytes; we're done
536
  if (target_start >= target_length || source_start >= source_end)
537
    return args.GetReturnValue().Set(0);
538
539
  if (source_start > source.length())
540
    return THROW_ERR_OUT_OF_RANGE(
541
        env, "The value of \"sourceStart\" is out of range.");
542
543
  if (source_end - source_start > target_length - target_start)
544
    source_end = source_start + target_length - target_start;
545
546
  uint32_t to_copy = std::min(
547
      std::min(source_end - source_start, target_length - target_start),
548
      source.length() - source_start);
549
550
  memmove(target_data + target_start, source.data() + source_start, to_copy);
551
  args.GetReturnValue().Set(to_copy);
552
}
553
554
555
void Fill(const FunctionCallbackInfo<Value>& args) {
556
  Environment* env = Environment::GetCurrent(args);
557
  Local<Context> ctx = env->context();
558
559
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
560
  SPREAD_BUFFER_ARG(args[0], ts_obj);
561
562
  size_t start;
563
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &start));
564
  size_t end;
565
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &end));
566
567
  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
  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
  if (Buffer::HasInstance(args[1])) {
578
    SPREAD_BUFFER_ARG(args[1], fill_obj);
579
    str_length = fill_obj_length;
580
    memcpy(
581
        ts_obj_data + start, fill_obj_data, std::min(str_length, fill_length));
582
    goto start_fill;
583
  }
584
585
  // Then coerce everything that's not a string.
586
  if (!args[1]->IsString()) {
587
    uint32_t val;
588
    if (!args[1]->Uint32Value(ctx).To(&val)) return;
589
    int value = val & 255;
590
    memset(ts_obj_data + start, value, fill_length);
591
    return;
592
  }
593
594
  str_obj = args[1]->ToString(env->context()).ToLocalChecked();
595
  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
  if (enc == UTF8) {
600
    str_length = str_obj->Utf8Length(env->isolate());
601
    node::Utf8Value str(env->isolate(), args[1]);
602
    memcpy(ts_obj_data + start, *str, std::min(str_length, fill_length));
603
604
  } else if (enc == UCS2) {
605
    str_length = str_obj->Length() * sizeof(uint16_t);
606
    node::TwoByteValue str(env->isolate(), args[1]);
607
    if (IsBigEndian())
608
      SwapBytes16(reinterpret_cast<char*>(&str[0]), str_length);
609
610
    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
    str_length = StringBytes::Write(env->isolate(),
617
                                    ts_obj_data + start,
618
                                    fill_length,
619
                                    str_obj,
620
                                    enc,
621
                                    nullptr);
622
  }
623
624
start_fill:
625
626
  if (str_length >= fill_length)
627
    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
  if (str_length == 0)
635
    return args.GetReturnValue().Set(-1);
636
637
  size_t in_there = str_length;
638
  char* ptr = ts_obj_data + start + str_length;
639
640
  while (in_there < fill_length - in_there) {
641
    memcpy(ptr, ts_obj_data + start, in_there);
642
    ptr += in_there;
643
    in_there *= 2;
644
  }
645
646
  if (in_there < fill_length) {
647
    memcpy(ptr, ts_obj_data + start, fill_length - in_there);
648
  }
649
}
650
651
652
template <encoding encoding>
653
14521
void StringWrite(const FunctionCallbackInfo<Value>& args) {
654
14521
  Environment* env = Environment::GetCurrent(args);
655
656



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



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



72605
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "argument");
660
58084
661



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



14521
663
  size_t offset;
664
  size_t max_length;
665
666







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



14521
  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







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



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



29042
  args.GetReturnValue().Set(written);
687
}
688
689
1209
void ByteLengthUtf8(const FunctionCallbackInfo<Value> &args) {
690
1209
  Environment* env = Environment::GetCurrent(args);
691
3627
  CHECK(args[0]->IsString());
692
693
  // Fast case: avoid StringBytes on UTF8 string. Jump to v8.
694
7254
  args.GetReturnValue().Set(args[0].As<String>()->Utf8Length(env->isolate()));
695
1209
}
696
697
// Normalize val to be an integer in the range of [1, -1] since
698
// implementations of memcmp() can vary by platform.
699
static int normalizeCompareVal(int val, size_t a_length, size_t b_length) {
700
  if (val == 0) {
701
    if (a_length > b_length)
702
      return 1;
703
    else if (a_length < b_length)
704
      return -1;
705
  } else {
706
    if (val > 0)
707
      return 1;
708
    else
709
      return -1;
710
  }
711
  return val;
712
}
713
714
void CompareOffset(const FunctionCallbackInfo<Value> &args) {
715
  Environment* env = Environment::GetCurrent(args);
716
717
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
718
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
719
  ArrayBufferViewContents<char> source(args[0]);
720
  ArrayBufferViewContents<char> target(args[1]);
721
722
  size_t target_start = 0;
723
  size_t source_start = 0;
724
  size_t source_end = 0;
725
  size_t target_end = 0;
726
727
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &target_start));
728
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &source_start));
729
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], target.length(),
730
                                          &target_end));
731
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[5], source.length(),
732
                                          &source_end));
733
734
  if (source_start > source.length())
735
    return THROW_ERR_OUT_OF_RANGE(
736
        env, "The value of \"sourceStart\" is out of range.");
737
  if (target_start > target.length())
738
    return THROW_ERR_OUT_OF_RANGE(
739
        env, "The value of \"targetStart\" is out of range.");
740
741
  CHECK_LE(source_start, source_end);
742
  CHECK_LE(target_start, target_end);
743
744
  size_t to_cmp =
745
      std::min(std::min(source_end - source_start, target_end - target_start),
746
               source.length() - source_start);
747
748
  int val = normalizeCompareVal(to_cmp > 0 ?
749
                                  memcmp(source.data() + source_start,
750
                                         target.data() + target_start,
751
                                         to_cmp) : 0,
752
                                source_end - source_start,
753
                                target_end - target_start);
754
755
  args.GetReturnValue().Set(val);
756
}
757
758
void Compare(const FunctionCallbackInfo<Value> &args) {
759
  Environment* env = Environment::GetCurrent(args);
760
761
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
762
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
763
  ArrayBufferViewContents<char> a(args[0]);
764
  ArrayBufferViewContents<char> b(args[1]);
765
766
  size_t cmp_length = std::min(a.length(), b.length());
767
768
  int val = normalizeCompareVal(cmp_length > 0 ?
769
                                memcmp(a.data(), b.data(), cmp_length) : 0,
770
                                a.length(), b.length());
771
  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
int64_t IndexOfOffset(size_t length,
779
                      int64_t offset_i64,
780
                      int64_t needle_length,
781
                      bool is_forward) {
782
  int64_t length_i64 = static_cast<int64_t>(length);
783
  if (offset_i64 < 0) {
784
    if (offset_i64 + length_i64 >= 0) {
785
      // Negative offsets count backwards from the end of the buffer.
786
      return length_i64 + offset_i64;
787
    } else if (is_forward || needle_length == 0) {
788
      // indexOf from before the start of the buffer: search the whole buffer.
789
      return 0;
790
    } else {
791
      // lastIndexOf from before the start of the buffer: no match.
792
      return -1;
793
    }
794
  } else {
795
    if (offset_i64 + needle_length <= length_i64) {
796
      // Valid positive offset.
797
      return offset_i64;
798
    } else if (needle_length == 0) {
799
      // Out of buffer bounds, but empty needle: point to end of buffer.
800
      return length_i64;
801
    } else if (is_forward) {
802
      // indexOf from past the end of the buffer: no match.
803
      return -1;
804
    } else {
805
      // lastIndexOf from past the end of the buffer: search the whole buffer.
806
      return length_i64 - 1;
807
    }
808
  }
809
}
810
811
void IndexOfString(const FunctionCallbackInfo<Value>& args) {
812
  Environment* env = Environment::GetCurrent(args);
813
  Isolate* isolate = env->isolate();
814
815
  CHECK(args[1]->IsString());
816
  CHECK(args[2]->IsNumber());
817
  CHECK(args[3]->IsInt32());
818
  CHECK(args[4]->IsBoolean());
819
820
  enum encoding enc = static_cast<enum encoding>(args[3].As<Int32>()->Value());
821
822
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
823
  ArrayBufferViewContents<char> buffer(args[0]);
824
825
  Local<String> needle = args[1].As<String>();
826
  int64_t offset_i64 = args[2].As<Integer>()->Value();
827
  bool is_forward = args[4]->IsTrue();
828
829
  const char* haystack = buffer.data();
830
  // Round down to the nearest multiple of 2 in case of UCS2.
831
  const size_t haystack_length = (enc == UCS2) ?
832
      buffer.length() &~ 1 : buffer.length();  // NOLINT(whitespace/operators)
833
834
  size_t needle_length;
835
  if (!StringBytes::Size(isolate, needle, enc).To(&needle_length)) return;
836
837
  int64_t opt_offset = IndexOfOffset(haystack_length,
838
                                     offset_i64,
839
                                     needle_length,
840
                                     is_forward);
841
842
  if (needle_length == 0) {
843
    // Match String#indexOf() and String#lastIndexOf() behavior.
844
    args.GetReturnValue().Set(static_cast<double>(opt_offset));
845
    return;
846
  }
847
848
  if (haystack_length == 0) {
849
    return args.GetReturnValue().Set(-1);
850
  }
851
852
  if (opt_offset <= -1) {
853
    return args.GetReturnValue().Set(-1);
854
  }
855
  size_t offset = static_cast<size_t>(opt_offset);
856
  CHECK_LT(offset, haystack_length);
857
  if ((is_forward && needle_length + offset > haystack_length) ||
858
      needle_length > haystack_length) {
859
    return args.GetReturnValue().Set(-1);
860
  }
861
862
  size_t result = haystack_length;
863
864
  if (enc == UCS2) {
865
    String::Value needle_value(isolate, needle);
866
    if (*needle_value == nullptr)
867
      return args.GetReturnValue().Set(-1);
868
869
    if (haystack_length < 2 || needle_value.length() < 1) {
870
      return args.GetReturnValue().Set(-1);
871
    }
872
873
    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
      result = SearchString(reinterpret_cast<const uint16_t*>(haystack),
890
                            haystack_length / 2,
891
                            reinterpret_cast<const uint16_t*>(*needle_value),
892
                            needle_value.length(),
893
                            offset / 2,
894
                            is_forward);
895
    }
896
    result *= 2;
897
  } else if (enc == UTF8) {
898
    String::Utf8Value needle_value(isolate, needle);
899
    if (*needle_value == nullptr)
900
      return args.GetReturnValue().Set(-1);
901
902
    result = SearchString(reinterpret_cast<const uint8_t*>(haystack),
903
                          haystack_length,
904
                          reinterpret_cast<const uint8_t*>(*needle_value),
905
                          needle_length,
906
                          offset,
907
                          is_forward);
908
  } else if (enc == LATIN1) {
909
    uint8_t* needle_data = node::UncheckedMalloc<uint8_t>(needle_length);
910
    if (needle_data == nullptr) {
911
      return args.GetReturnValue().Set(-1);
912
    }
913
    needle->WriteOneByte(
914
        isolate, needle_data, 0, needle_length, String::NO_NULL_TERMINATION);
915
916
    result = SearchString(reinterpret_cast<const uint8_t*>(haystack),
917
                          haystack_length,
918
                          needle_data,
919
                          needle_length,
920
                          offset,
921
                          is_forward);
922
    free(needle_data);
923
  }
924
925
  args.GetReturnValue().Set(
926
      result == haystack_length ? -1 : static_cast<int>(result));
927
}
928
929
void IndexOfBuffer(const FunctionCallbackInfo<Value>& args) {
930
  CHECK(args[1]->IsObject());
931
  CHECK(args[2]->IsNumber());
932
  CHECK(args[3]->IsInt32());
933
  CHECK(args[4]->IsBoolean());
934
935
  enum encoding enc = static_cast<enum encoding>(args[3].As<Int32>()->Value());
936
937
  THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[0]);
938
  THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[1]);
939
  ArrayBufferViewContents<char> haystack_contents(args[0]);
940
  ArrayBufferViewContents<char> needle_contents(args[1]);
941
  int64_t offset_i64 = args[2].As<Integer>()->Value();
942
  bool is_forward = args[4]->IsTrue();
943
944
  const char* haystack = haystack_contents.data();
945
  const size_t haystack_length = haystack_contents.length();
946
  const char* needle = needle_contents.data();
947
  const size_t needle_length = needle_contents.length();
948
949
  int64_t opt_offset = IndexOfOffset(haystack_length,
950
                                     offset_i64,
951
                                     needle_length,
952
                                     is_forward);
953
954
  if (needle_length == 0) {
955
    // Match String#indexOf() and String#lastIndexOf() behavior.
956
    args.GetReturnValue().Set(static_cast<double>(opt_offset));
957
    return;
958
  }
959
960
  if (haystack_length == 0) {
961
    return args.GetReturnValue().Set(-1);
962
  }
963
964
  if (opt_offset <= -1) {
965
    return args.GetReturnValue().Set(-1);
966
  }
967
  size_t offset = static_cast<size_t>(opt_offset);
968
  CHECK_LT(offset, haystack_length);
969
  if ((is_forward && needle_length + offset > haystack_length) ||
970
      needle_length > haystack_length) {
971
    return args.GetReturnValue().Set(-1);
972
  }
973
974
  size_t result = haystack_length;
975
976
  if (enc == UCS2) {
977
    if (haystack_length < 2 || needle_length < 2) {
978
      return args.GetReturnValue().Set(-1);
979
    }
980
    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
        is_forward);
987
    result *= 2;
988
  } else {
989
    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
        is_forward);
996
  }
997
998
  args.GetReturnValue().Set(
999
      result == haystack_length ? -1 : static_cast<int>(result));
1000
}
1001
1002
void IndexOfNumber(const FunctionCallbackInfo<Value>& args) {
1003
  CHECK(args[1]->IsUint32());
1004
  CHECK(args[2]->IsNumber());
1005
  CHECK(args[3]->IsBoolean());
1006
1007
  THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[0]);
1008
  ArrayBufferViewContents<char> buffer(args[0]);
1009
1010
  uint32_t needle = args[1].As<Uint32>()->Value();
1011
  int64_t offset_i64 = args[2].As<Integer>()->Value();
1012
  bool is_forward = args[3]->IsTrue();
1013
1014
  int64_t opt_offset =
1015
      IndexOfOffset(buffer.length(), offset_i64, 1, is_forward);
1016
  if (opt_offset <= -1 || buffer.length() == 0) {
1017
    return args.GetReturnValue().Set(-1);
1018
  }
1019
  size_t offset = static_cast<size_t>(opt_offset);
1020
  CHECK_LT(offset, buffer.length());
1021
1022
  const void* ptr;
1023
  if (is_forward) {
1024
    ptr = memchr(buffer.data() + offset, needle, buffer.length() - offset);
1025
  } else {
1026
    ptr = node::stringsearch::MemrchrFill(buffer.data(), needle, offset + 1);
1027
  }
1028
  const char* ptr_char = static_cast<const char*>(ptr);
1029
  args.GetReturnValue().Set(ptr ? static_cast<int>(ptr_char - buffer.data())
1030
                                : -1);
1031
}
1032
1033
1034
void Swap16(const FunctionCallbackInfo<Value>& args) {
1035
  Environment* env = Environment::GetCurrent(args);
1036
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1037
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1038
  SwapBytes16(ts_obj_data, ts_obj_length);
1039
  args.GetReturnValue().Set(args[0]);
1040
}
1041
1042
1043
void Swap32(const FunctionCallbackInfo<Value>& args) {
1044
  Environment* env = Environment::GetCurrent(args);
1045
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1046
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1047
  SwapBytes32(ts_obj_data, ts_obj_length);
1048
  args.GetReturnValue().Set(args[0]);
1049
}
1050
1051
1052
void Swap64(const FunctionCallbackInfo<Value>& args) {
1053
  Environment* env = Environment::GetCurrent(args);
1054
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1055
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1056
  SwapBytes64(ts_obj_data, ts_obj_length);
1057
  args.GetReturnValue().Set(args[0]);
1058
}
1059
1060
1061
// Encode a single string to a UTF-8 Uint8Array (not Buffer).
1062
// Used in TextEncoder.prototype.encode.
1063
static void EncodeUtf8String(const FunctionCallbackInfo<Value>& args) {
1064
  Environment* env = Environment::GetCurrent(args);
1065
  Isolate* isolate = env->isolate();
1066
  CHECK_GE(args.Length(), 1);
1067
  CHECK(args[0]->IsString());
1068
1069
  Local<String> str = args[0].As<String>();
1070
  size_t length = str->Utf8Length(isolate);
1071
  AllocatedBuffer buf = AllocatedBuffer::AllocateManaged(env, length);
1072
  str->WriteUtf8(isolate,
1073
                 buf.data(),
1074
                 -1,  // We are certain that `data` is sufficiently large
1075
                 nullptr,
1076
                 String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8);
1077
  auto array = Uint8Array::New(buf.ToArrayBuffer(), 0, length);
1078
  args.GetReturnValue().Set(array);
1079
}
1080
1081
1082
static void EncodeInto(const FunctionCallbackInfo<Value>& args) {
1083
  Environment* env = Environment::GetCurrent(args);
1084
  Isolate* isolate = env->isolate();
1085
  CHECK_GE(args.Length(), 3);
1086
  CHECK(args[0]->IsString());
1087
  CHECK(args[1]->IsUint8Array());
1088
  CHECK(args[2]->IsUint32Array());
1089
1090
  Local<String> source = args[0].As<String>();
1091
1092
  Local<Uint8Array> dest = args[1].As<Uint8Array>();
1093
  Local<ArrayBuffer> buf = dest->Buffer();
1094
  char* write_result =
1095
      static_cast<char*>(buf->GetBackingStore()->Data()) + dest->ByteOffset();
1096
  size_t dest_length = dest->ByteLength();
1097
1098
  // results = [ read, written ]
1099
  Local<Uint32Array> result_arr = args[2].As<Uint32Array>();
1100
  uint32_t* results = reinterpret_cast<uint32_t*>(
1101
      static_cast<char*>(result_arr->Buffer()->GetBackingStore()->Data()) +
1102
      result_arr->ByteOffset());
1103
1104
  int nchars;
1105
  int written = source->WriteUtf8(
1106
      isolate,
1107
      write_result,
1108
      dest_length,
1109
      &nchars,
1110
      String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8);
1111
  results[0] = nchars;
1112
  results[1] = written;
1113
}
1114
1115
1116
52
void SetBufferPrototype(const FunctionCallbackInfo<Value>& args) {
1117
52
  Environment* env = Environment::GetCurrent(args);
1118
1119
104
  CHECK(args[0]->IsObject());
1120
104
  Local<Object> proto = args[0].As<Object>();
1121
52
  env->set_buffer_prototype_object(proto);
1122
52
}
1123
1124
172
void GetZeroFillToggle(const FunctionCallbackInfo<Value>& args) {
1125
172
  Environment* env = Environment::GetCurrent(args);
1126
172
  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
172
  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
58
    ab = ArrayBuffer::New(env->isolate(), sizeof(uint32_t));
1135
  } else {
1136
114
    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
334
                                     [](void*, size_t, void*) {},
1141
228
                                     nullptr);
1142
114
    ab = ArrayBuffer::New(env->isolate(), std::move(backing));
1143
  }
1144
1145
344
  ab->SetPrivate(
1146
      env->context(),
1147
      env->untransferable_object_private_symbol(),
1148
516
      True(env->isolate())).Check();
1149
1150
516
  args.GetReturnValue().Set(Uint32Array::New(ab, 0, 1));
1151
172
}
1152
1153
52
void Initialize(Local<Object> target,
1154
                Local<Value> unused,
1155
                Local<Context> context,
1156
                void* priv) {
1157
52
  Environment* env = Environment::GetCurrent(context);
1158
1159
52
  env->SetMethod(target, "setBufferPrototype", SetBufferPrototype);
1160
52
  env->SetMethodNoSideEffect(target, "createFromString", CreateFromString);
1161
1162
52
  env->SetMethodNoSideEffect(target, "byteLengthUtf8", ByteLengthUtf8);
1163
52
  env->SetMethod(target, "copy", Copy);
1164
52
  env->SetMethodNoSideEffect(target, "compare", Compare);
1165
52
  env->SetMethodNoSideEffect(target, "compareOffset", CompareOffset);
1166
52
  env->SetMethod(target, "fill", Fill);
1167
52
  env->SetMethodNoSideEffect(target, "indexOfBuffer", IndexOfBuffer);
1168
52
  env->SetMethodNoSideEffect(target, "indexOfNumber", IndexOfNumber);
1169
52
  env->SetMethodNoSideEffect(target, "indexOfString", IndexOfString);
1170
1171
52
  env->SetMethod(target, "swap16", Swap16);
1172
52
  env->SetMethod(target, "swap32", Swap32);
1173
52
  env->SetMethod(target, "swap64", Swap64);
1174
1175
52
  env->SetMethod(target, "encodeInto", EncodeInto);
1176
52
  env->SetMethodNoSideEffect(target, "encodeUtf8String", EncodeUtf8String);
1177
1178
104
  target->Set(env->context(),
1179
              FIXED_ONE_BYTE_STRING(env->isolate(), "kMaxLength"),
1180
260
              Number::New(env->isolate(), kMaxLength)).Check();
1181
1182
104
  target->Set(env->context(),
1183
              FIXED_ONE_BYTE_STRING(env->isolate(), "kStringMaxLength"),
1184
260
              Integer::New(env->isolate(), String::kMaxLength)).Check();
1185
1186
52
  env->SetMethodNoSideEffect(target, "asciiSlice", StringSlice<ASCII>);
1187
52
  env->SetMethodNoSideEffect(target, "base64Slice", StringSlice<BASE64>);
1188
52
  env->SetMethodNoSideEffect(target, "base64urlSlice", StringSlice<BASE64URL>);
1189
52
  env->SetMethodNoSideEffect(target, "latin1Slice", StringSlice<LATIN1>);
1190
52
  env->SetMethodNoSideEffect(target, "hexSlice", StringSlice<HEX>);
1191
52
  env->SetMethodNoSideEffect(target, "ucs2Slice", StringSlice<UCS2>);
1192
52
  env->SetMethodNoSideEffect(target, "utf8Slice", StringSlice<UTF8>);
1193
1194
52
  env->SetMethod(target, "asciiWrite", StringWrite<ASCII>);
1195
52
  env->SetMethod(target, "base64Write", StringWrite<BASE64>);
1196
52
  env->SetMethod(target, "base64urlWrite", StringWrite<BASE64URL>);
1197
52
  env->SetMethod(target, "latin1Write", StringWrite<LATIN1>);
1198
52
  env->SetMethod(target, "hexWrite", StringWrite<HEX>);
1199
52
  env->SetMethod(target, "ucs2Write", StringWrite<UCS2>);
1200
52
  env->SetMethod(target, "utf8Write", StringWrite<UTF8>);
1201
1202
52
  env->SetMethod(target, "getZeroFillToggle", GetZeroFillToggle);
1203
1204
52
  Blob::Initialize(env, target);
1205
52
}
1206
1207
}  // anonymous namespace
1208
1209
107
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
1210
107
  registry->Register(SetBufferPrototype);
1211
107
  registry->Register(CreateFromString);
1212
1213
107
  registry->Register(ByteLengthUtf8);
1214
107
  registry->Register(Copy);
1215
107
  registry->Register(Compare);
1216
107
  registry->Register(CompareOffset);
1217
107
  registry->Register(Fill);
1218
107
  registry->Register(IndexOfBuffer);
1219
107
  registry->Register(IndexOfNumber);
1220
107
  registry->Register(IndexOfString);
1221
1222
107
  registry->Register(Swap16);
1223
107
  registry->Register(Swap32);
1224
107
  registry->Register(Swap64);
1225
1226
107
  registry->Register(EncodeInto);
1227
107
  registry->Register(EncodeUtf8String);
1228
1229
107
  registry->Register(StringSlice<ASCII>);
1230
107
  registry->Register(StringSlice<BASE64>);
1231
107
  registry->Register(StringSlice<BASE64URL>);
1232
107
  registry->Register(StringSlice<LATIN1>);
1233
107
  registry->Register(StringSlice<HEX>);
1234
107
  registry->Register(StringSlice<UCS2>);
1235
107
  registry->Register(StringSlice<UTF8>);
1236
1237
107
  registry->Register(StringWrite<ASCII>);
1238
107
  registry->Register(StringWrite<BASE64>);
1239
107
  registry->Register(StringWrite<BASE64URL>);
1240
107
  registry->Register(StringWrite<LATIN1>);
1241
107
  registry->Register(StringWrite<HEX>);
1242
107
  registry->Register(StringWrite<UCS2>);
1243
107
  registry->Register(StringWrite<UTF8>);
1244
107
  registry->Register(GetZeroFillToggle);
1245
1246
107
  Blob::RegisterExternalReferences(registry);
1247
107
  FixedSizeBlobCopyJob::RegisterExternalReferences(registry);
1248
107
}
1249
1250
}  // namespace Buffer
1251
}  // namespace node
1252
1253
115
NODE_MODULE_CONTEXT_AWARE_INTERNAL(buffer, node::Buffer::Initialize)
1254

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