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: 2020-12-12 04:11:07 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
962
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
493
Local<ArrayBuffer> CallbackInfo::CreateTrackedArrayBuffer(
107
    Environment* env,
108
    char* data,
109
    size_t length,
110
    FreeCallback callback,
111
    void* hint) {
112
493
  CHECK_NOT_NULL(callback);
113

493
  CHECK_IMPLIES(data == nullptr, length == 0);
114
115
493
  CallbackInfo* self = new CallbackInfo(env, callback, data, hint);
116
  std::unique_ptr<BackingStore> bs =
117
1469
      ArrayBuffer::NewBackingStore(data, length, [](void*, size_t, void* arg) {
118
488
        static_cast<CallbackInfo*>(arg)->OnBackingStoreFree();
119
2455
      }, self);
120
493
  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
493
  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
490
    self->persistent_.Reset(env->isolate(), ab);
130
490
    self->persistent_.SetWeak();
131
  }
132
133
986
  return ab;
134
}
135
136
137
493
CallbackInfo::CallbackInfo(Environment* env,
138
                           FreeCallback callback,
139
                           char* data,
140
493
                           void* hint)
141
    : callback_(callback),
142
      data_(data),
143
      hint_(hint),
144
986
      env_(env) {
145
493
  env->AddCleanupHook(CleanupHook, this);
146
493
  env->isolate()->AdjustAmountOfExternalAllocatedMemory(sizeof(*this));
147
493
}
148
149
251
void CallbackInfo::CleanupHook(void* data) {
150
251
  CallbackInfo* self = static_cast<CallbackInfo*>(data);
151
152
  {
153
502
    HandleScope handle_scope(self->env_->isolate());
154
502
    Local<ArrayBuffer> ab = self->persistent_.Get(self->env_->isolate());
155

502
    if (!ab.IsEmpty() && ab->IsDetachable()) {
156
251
      ab->Detach();
157
251
      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
251
  self->CallAndResetCallback();
164
251
}
165
166
732
void CallbackInfo::CallAndResetCallback() {
167
  FreeCallback callback;
168
  {
169
1464
    Mutex::ScopedLock lock(mutex_);
170
732
    callback = callback_;
171
732
    callback_ = nullptr;
172
  }
173
732
  if (callback != nullptr) {
174
    // Clean up all Environment-related state and run the callback.
175
481
    env_->RemoveCleanupHook(CleanupHook, this);
176
481
    int64_t change_in_bytes = -static_cast<int64_t>(sizeof(*this));
177
481
    env_->isolate()->AdjustAmountOfExternalAllocatedMemory(change_in_bytes);
178
179
481
    callback(data_, hint_);
180
  }
181
732
}
182
183
491
void CallbackInfo::OnBackingStoreFree() {
184
  // This method should always release the memory for `this`.
185
982
  std::unique_ptr<CallbackInfo> self { this };
186
982
  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
491
  if (callback_ == nullptr) return;
192
193
2926
  env_->SetImmediateThreadsafe([self = std::move(self)](Environment* env) {
194
481
    CHECK_EQ(self->env_, env);  // Consistency check.
195
196
481
    self->CallAndResetCallback();
197
972
  });
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
991342
inline MUST_USE_RESULT Maybe<bool> ParseArrayIndex(Environment* env,
204
                                                   Local<Value> arg,
205
                                                   size_t def,
206
                                                   size_t* ret) {
207
1982684
  if (arg->IsUndefined()) {
208
    *ret = def;
209
    return Just(true);
210
  }
211
212
  int64_t tmp_i;
213
2974026
  if (!arg->IntegerValue(env->context()).To(&tmp_i))
214
    return Nothing<bool>();
215
216
991342
  if (tmp_i < 0)
217
4
    return Just(false);
218
219
  // Check that the result fits in a size_t.
220
991338
  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
991338
  *ret = static_cast<size_t>(tmp_i);
226
991338
  return Just(true);
227
}
228
229
}  // anonymous namespace
230
231
// Buffer methods
232
233
3433109
bool HasInstance(Local<Value> val) {
234
3433109
  return val->IsArrayBufferView();
235
}
236
237
238
247811
bool HasInstance(Local<Object> obj) {
239
247811
  return obj->IsArrayBufferView();
240
}
241
242
243
242261
char* Data(Local<Value> val) {
244
242261
  CHECK(val->IsArrayBufferView());
245
242261
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
246
726783
  return static_cast<char*>(ui->Buffer()->GetBackingStore()->Data()) +
247
484522
      ui->ByteOffset();
248
}
249
250
251
112841
char* Data(Local<Object> obj) {
252
112841
  return Data(obj.As<Value>());
253
}
254
255
256
103319
size_t Length(Local<Value> val) {
257
103319
  CHECK(val->IsArrayBufferView());
258
103319
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
259
103319
  return ui->ByteLength();
260
}
261
262
263
111548
size_t Length(Local<Object> obj) {
264
111548
  CHECK(obj->IsArrayBufferView());
265
111548
  Local<ArrayBufferView> ui = obj.As<ArrayBufferView>();
266
111548
  return ui->ByteLength();
267
}
268
269
270
13433
MaybeLocal<Uint8Array> New(Environment* env,
271
                           Local<ArrayBuffer> ab,
272
                           size_t byte_offset,
273
                           size_t length) {
274
26866
  CHECK(!env->buffer_prototype_object().IsEmpty());
275
13433
  Local<Uint8Array> ui = Uint8Array::New(ab, byte_offset, length);
276
  Maybe<bool> mb =
277
40299
      ui->SetPrototype(env->context(), env->buffer_prototype_object());
278
13433
  if (mb.IsNothing())
279
    return MaybeLocal<Uint8Array>();
280
13433
  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
1272
MaybeLocal<Object> New(Environment* env, size_t length) {
345
1272
  EscapableHandleScope scope(env->isolate());
346
347
  // V8 currently only allows a maximum Typed Array index of max Smi.
348
1272
  if (length > kMaxLength) {
349
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
350
    return Local<Object>();
351
  }
352
353
  return scope.EscapeMaybe(
354
2544
      AllocatedBuffer::AllocateManaged(env, length).ToBuffer());
355
}
356
357
358
3124
MaybeLocal<Object> Copy(Isolate* isolate, const char* data, size_t length) {
359
3124
  EscapableHandleScope handle_scope(isolate);
360
3124
  Environment* env = Environment::GetCurrent(isolate);
361
3124
  if (env == nullptr) {
362
1
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
363
1
    return MaybeLocal<Object>();
364
  }
365
  Local<Object> obj;
366
6246
  if (Buffer::Copy(env, data, length).ToLocal(&obj))
367
3123
    return handle_scope.Escape(obj);
368
  return Local<Object>();
369
}
370
371
372
7891
MaybeLocal<Object> Copy(Environment* env, const char* data, size_t length) {
373
7891
  EscapableHandleScope scope(env->isolate());
374
375
  // V8 currently only allows a maximum Typed Array index of max Smi.
376
7891
  if (length > kMaxLength) {
377
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
378
    return Local<Object>();
379
  }
380
381
15782
  AllocatedBuffer ret = AllocatedBuffer::AllocateManaged(env, length);
382
7891
  if (length > 0) {
383
7669
    memcpy(ret.data(), data, length);
384
  }
385
386
7891
  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
493
MaybeLocal<Object> New(Environment* env,
408
                       char* data,
409
                       size_t length,
410
                       FreeCallback callback,
411
                       void* hint) {
412
493
  EscapableHandleScope scope(env->isolate());
413
414
493
  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
493
      CallbackInfo::CreateTrackedArrayBuffer(env, data, length, callback, hint);
422
1479
  if (ab->SetPrivate(env->context(),
423
                     env->untransferable_object_private_symbol(),
424
1479
                     True(env->isolate())).IsNothing()) {
425
    return Local<Object>();
426
  }
427
493
  MaybeLocal<Uint8Array> maybe_ui = Buffer::New(env, ab, 0, length);
428
429
  Local<Uint8Array> ui;
430
493
  if (!maybe_ui.ToLocal(&ui))
431
    return MaybeLocal<Object>();
432
433
493
  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
464
MaybeLocal<Object> New(Environment* env,
455
                       char* data,
456
                       size_t length) {
457
464
  if (length > 0) {
458
463
    CHECK_NOT_NULL(data);
459
463
    CHECK(length <= kMaxLength);
460
  }
461
462
1368
  auto free_callback = [](char* data, void* hint) { free(data); };
463
464
  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
102377
void StringSlice(const FunctionCallbackInfo<Value>& args) {
481
102377
  Environment* env = Environment::GetCurrent(args);
482
102377
  Isolate* isolate = env->isolate();
483
484



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



102377
  if (buffer.length() == 0)
488
346
    return args.GetReturnValue().SetEmptyString();
489
490
102204
  size_t start = 0;
491
102204
  size_t end = 0;
492






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






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



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






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



102204
  if (ret.IsEmpty()) {
506



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

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

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

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

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

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

322
  size_t end;
563

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

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



145438
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
655



290868
  SPREAD_BUFFER_ARG(args.This(), ts_obj);
656
657



727170
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "argument");
658
581732
659



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



145431
661
  size_t offset;
662
  size_t max_length;
663
664






581736
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], 0, &offset));
665



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






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



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



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

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

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

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

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

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

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

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

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

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

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

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

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

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

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