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

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

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



105218
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
485
105074
  ArrayBufferViewContents<char> buffer(args.This());
486
487



105075
  if (buffer.length() == 0)
488
274
    return args.GetReturnValue().SetEmptyString();
489
490
104938
  size_t start = 0;
491
104938
  size_t end = 0;
492






419750
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[0], 0, &start));
493






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



104938
  if (end < start) end = start;
495






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



104938
  if (!maybe_ret.ToLocal(&ret)) {
507



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

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

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

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

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

1263
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &start));
563

322
  size_t end;
564

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

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



139623
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
656



279238
  SPREAD_BUFFER_ARG(args.This(), ts_obj);
657
658



698095
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "argument");
659
558472
660



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



139616
662
  size_t offset;
663
  size_t max_length;
664
665






558476
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], 0, &offset));
666



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






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



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



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

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

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

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

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

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

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

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

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

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

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

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

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

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

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