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: 600 659 91.0 %
Date: 2021-06-05 04:12:00 Branches: 422 714 59.1 %

Line Branch Exec Source
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
#include "node_buffer.h"
23
#include "allocated_buffer-inl.h"
24
#include "node.h"
25
#include "node_blob.h"
26
#include "node_errors.h"
27
#include "node_external_reference.h"
28
#include "node_internals.h"
29
30
#include "env-inl.h"
31
#include "string_bytes.h"
32
#include "string_search.h"
33
#include "util-inl.h"
34
#include "v8.h"
35
36
#include <cstring>
37
#include <climits>
38
39
#define THROW_AND_RETURN_UNLESS_BUFFER(env, obj)                            \
40
  THROW_AND_RETURN_IF_NOT_BUFFER(env, obj, "argument")                      \
41
42
#define THROW_AND_RETURN_IF_OOB(r)                                          \
43
  do {                                                                      \
44
    if ((r).IsNothing()) return;                                            \
45
    if (!(r).FromJust())                                                    \
46
      return node::THROW_ERR_OUT_OF_RANGE(env, "Index out of range");       \
47
  } while (0)                                                               \
48
49
namespace node {
50
namespace Buffer {
51
52
using v8::ArrayBuffer;
53
using v8::ArrayBufferView;
54
using v8::BackingStore;
55
using v8::Context;
56
using v8::EscapableHandleScope;
57
using v8::FunctionCallbackInfo;
58
using v8::Global;
59
using v8::HandleScope;
60
using v8::Int32;
61
using v8::Integer;
62
using v8::Isolate;
63
using v8::Just;
64
using v8::Local;
65
using v8::Maybe;
66
using v8::MaybeLocal;
67
using v8::Nothing;
68
using v8::Number;
69
using v8::Object;
70
using v8::String;
71
using v8::Uint32;
72
using v8::Uint32Array;
73
using v8::Uint8Array;
74
using v8::Value;
75
76
namespace {
77
78
1309
class CallbackInfo {
79
 public:
80
  static inline Local<ArrayBuffer> CreateTrackedArrayBuffer(
81
      Environment* env,
82
      char* data,
83
      size_t length,
84
      FreeCallback callback,
85
      void* hint);
86
87
  CallbackInfo(const CallbackInfo&) = delete;
88
  CallbackInfo& operator=(const CallbackInfo&) = delete;
89
90
 private:
91
  static void CleanupHook(void* data);
92
  inline void OnBackingStoreFree();
93
  inline void CallAndResetCallback();
94
  inline CallbackInfo(Environment* env,
95
                      FreeCallback callback,
96
                      char* data,
97
                      void* hint);
98
  Global<ArrayBuffer> persistent_;
99
  Mutex mutex_;  // Protects callback_.
100
  FreeCallback callback_;
101
  char* const data_;
102
  void* const hint_;
103
  Environment* const env_;
104
};
105
106
107
658
Local<ArrayBuffer> CallbackInfo::CreateTrackedArrayBuffer(
108
    Environment* env,
109
    char* data,
110
    size_t length,
111
    FreeCallback callback,
112
    void* hint) {
113
658
  CHECK_NOT_NULL(callback);
114

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

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



110820
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
494
110625
  ArrayBufferViewContents<char> buffer(args.This());
495
496



110625
  if (buffer.length() == 0)
497
376
    return args.GetReturnValue().SetEmptyString();
498
499
110437
  size_t start = 0;
500
110437
  size_t end = 0;
501







441748
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[0], 0, &start));
502







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



110437
  if (end < start) end = start;
504







331311
  THROW_AND_RETURN_IF_OOB(Just(end <= buffer.length()));
505
110437
  size_t length = end - start;
506
507
  Local<Value> error;
508
  MaybeLocal<Value> maybe_ret =
509
110437
      StringBytes::Encode(isolate,
510
110437
                          buffer.data() + start,
511
                          length,
512
                          encoding,
513
110437
                          &error);
514
  Local<Value> ret;
515



110437
  if (!maybe_ret.ToLocal(&ret)) {
516



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

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

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

65
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], source.length(),
541
                                          &source_end));
542
543
  // Copy 0 bytes; we're done
544

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

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

354
  size_t end;
573

881
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &end));
574
575
175
  size_t fill_length = end - start;
576
  Local<String> str_obj;
577
  size_t str_length;
578
  enum encoding enc;
579
580
  // OOB Check. Throw the error in JS.
581

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



131879
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
665



263748
  SPREAD_BUFFER_ARG(args.This(), ts_obj);
666
667



659370
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "argument");
668
527491
669



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



131870
671
131874
  size_t offset = 0;
672
131874
  size_t max_length = 0;
673
674







527496
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], 0, &offset));
675



131874
  if (offset > ts_obj_length) {
676
    return node::THROW_ERR_BUFFER_OUT_OF_BOUNDS(
677
        env, "\"offset\" is outside of buffer bounds");
678
  }
679
680







659370
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], ts_obj_length - offset,
681
                                          &max_length));
682
683
131874
  max_length = std::min(ts_obj_length - offset, max_length);
684
685



131874
  if (max_length == 0)
686
10
    return args.GetReturnValue().Set(0);
687
688
395607
  uint32_t written = StringBytes::Write(env->isolate(),
689
131869
                                        ts_obj_data + offset,
690
                                        max_length,
691
                                        str,
692
                                        encoding,
693
131869
                                        nullptr);
694



263738
  args.GetReturnValue().Set(written);
695
}
696
697
136706
void ByteLengthUtf8(const FunctionCallbackInfo<Value> &args) {
698
136706
  Environment* env = Environment::GetCurrent(args);
699
410118
  CHECK(args[0]->IsString());
700
701
  // Fast case: avoid StringBytes on UTF8 string. Jump to v8.
702
820236
  args.GetReturnValue().Set(args[0].As<String>()->Utf8Length(env->isolate()));
703
136706
}
704
705
// Normalize val to be an integer in the range of [1, -1] since
706
// implementations of memcmp() can vary by platform.
707
3538
static int normalizeCompareVal(int val, size_t a_length, size_t b_length) {
708
3538
  if (val == 0) {
709
3511
    if (a_length > b_length)
710
6
      return 1;
711
3505
    else if (a_length < b_length)
712
5
      return -1;
713
  } else {
714
27
    if (val > 0)
715
7
      return 1;
716
    else
717
20
      return -1;
718
  }
719
3500
  return val;
720
}
721
722
9
void CompareOffset(const FunctionCallbackInfo<Value> &args) {
723
9
  Environment* env = Environment::GetCurrent(args);
724
725
9
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
726
9
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
727
9
  ArrayBufferViewContents<char> source(args[0]);
728
9
  ArrayBufferViewContents<char> target(args[1]);
729
730
9
  size_t target_start = 0;
731
9
  size_t source_start = 0;
732
9
  size_t source_end = 0;
733
9
  size_t target_end = 0;
734
735

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

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

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

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

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

1742
  if ((is_forward && needle_length + offset > haystack_length) ||
866
870
      needle_length > haystack_length) {
867
30
    return args.GetReturnValue().Set(-1);
868
  }
869
870
857
  size_t result = haystack_length;
871
872
857
  if (enc == UCS2) {
873
170
    String::Value needle_value(isolate, needle);
874
85
    if (*needle_value == nullptr)
875
      return args.GetReturnValue().Set(-1);
876
877

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

392
  if ((is_forward && needle_length + offset > haystack_length) ||
978
195
      needle_length > haystack_length) {
979
14
    return args.GetReturnValue().Set(-1);
980
  }
981
982
190
  size_t result = haystack_length;
983
984
190
  if (enc == UCS2) {
985

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

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

4
1050
2
1051
2
void Swap32(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
  SwapBytes32(ts_obj_data, ts_obj_length);
1056
8
  args.GetReturnValue().Set(args[0]);
1057
8
}
1058

4
1059
2
1060
2
void Swap64(const FunctionCallbackInfo<Value>& args) {
1061
2
  Environment* env = Environment::GetCurrent(args);
1062
2
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1063
4
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1064
2
  SwapBytes64(ts_obj_data, ts_obj_length);
1065
8
  args.GetReturnValue().Set(args[0]);
1066
8
}
1067

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

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