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: 576 632 91.1 %
Date: 2020-07-19 22:14:24 Branches: 396 666 59.5 %

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

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

564
    if (!ab.IsEmpty() && ab->IsDetachable()) {
156
282
      ab->Detach();
157
282
      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
282
  self->CallAndResetCallback();
164
282
}
165
166
795
void CallbackInfo::CallAndResetCallback() {
167
  FreeCallback callback;
168
  {
169
1590
    Mutex::ScopedLock lock(mutex_);
170
795
    callback = callback_;
171
795
    callback_ = nullptr;
172
  }
173
795
  if (callback != nullptr) {
174
    // Clean up all Environment-related state and run the callback.
175
513
    env_->RemoveCleanupHook(CleanupHook, this);
176
513
    int64_t change_in_bytes = -static_cast<int64_t>(sizeof(*this));
177
513
    env_->isolate()->AdjustAmountOfExternalAllocatedMemory(change_in_bytes);
178
179
513
    callback(data_, hint_);
180
  }
181
795
}
182
183
515
void CallbackInfo::OnBackingStoreFree() {
184
  // This method should always release the memory for `this`.
185
1030
  std::unique_ptr<CallbackInfo> self { this };
186
1030
  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
515
  if (callback_ == nullptr) return;
192
193
3086
  env_->SetImmediateThreadsafe([self = std::move(self)](Environment* env) {
194
513
    CHECK_EQ(self->env_, env);  // Consistency check.
195
196
513
    self->CallAndResetCallback();
197
1028
  });
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
3720056
inline MUST_USE_RESULT Maybe<bool> ParseArrayIndex(Environment* env,
204
                                                   Local<Value> arg,
205
                                                   size_t def,
206
                                                   size_t* ret) {
207
7440112
  if (arg->IsUndefined()) {
208
    *ret = def;
209
    return Just(true);
210
  }
211
212
  int64_t tmp_i;
213
11160168
  if (!arg->IntegerValue(env->context()).To(&tmp_i))
214
    return Nothing<bool>();
215
216
3720056
  if (tmp_i < 0)
217
4
    return Just(false);
218
219
  // Check that the result fits in a size_t.
220
3720052
  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
3720052
  *ret = static_cast<size_t>(tmp_i);
226
3720052
  return Just(true);
227
}
228
229
}  // anonymous namespace
230
231
// Buffer methods
232
233
6362193
bool HasInstance(Local<Value> val) {
234
6362193
  return val->IsArrayBufferView();
235
}
236
237
238
929994
bool HasInstance(Local<Object> obj) {
239
929994
  return obj->IsArrayBufferView();
240
}
241
242
243
7680740
char* Data(Local<Value> val) {
244
7680740
  CHECK(val->IsArrayBufferView());
245
7680741
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
246
23042223
  return static_cast<char*>(ui->Buffer()->GetBackingStore()->Data()) +
247
15361482
      ui->ByteOffset();
248
}
249
250
251
143484
char* Data(Local<Object> obj) {
252
143484
  return Data(obj.As<Value>());
253
}
254
255
256
7509287
size_t Length(Local<Value> val) {
257
7509287
  CHECK(val->IsArrayBufferView());
258
7509287
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
259
7509287
  return ui->ByteLength();
260
}
261
262
263
140241
size_t Length(Local<Object> obj) {
264
140241
  CHECK(obj->IsArrayBufferView());
265
140241
  Local<ArrayBufferView> ui = obj.As<ArrayBufferView>();
266
140241
  return ui->ByteLength();
267
}
268
269
270
22078
MaybeLocal<Uint8Array> New(Environment* env,
271
                           Local<ArrayBuffer> ab,
272
                           size_t byte_offset,
273
                           size_t length) {
274
44157
  CHECK(!env->buffer_prototype_object().IsEmpty());
275
22079
  Local<Uint8Array> ui = Uint8Array::New(ab, byte_offset, length);
276
  Maybe<bool> mb =
277
66235
      ui->SetPrototype(env->context(), env->buffer_prototype_object());
278
22079
  if (mb.IsNothing())
279
    return MaybeLocal<Uint8Array>();
280
22079
  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
141
MaybeLocal<Object> New(Isolate* isolate,
297
                       Local<String> string,
298
                       enum encoding enc) {
299
141
  EscapableHandleScope scope(isolate);
300
301
  size_t length;
302
282
  if (!StringBytes::Size(isolate, string, enc).To(&length))
303
    return Local<Object>();
304
141
  size_t actual = 0;
305
141
  char* data = nullptr;
306
307
141
  if (length > 0) {
308
141
    data = UncheckedMalloc(length);
309
310
141
    if (data == nullptr) {
311
      THROW_ERR_MEMORY_ALLOCATION_FAILED(isolate);
312
      return Local<Object>();
313
    }
314
315
141
    actual = StringBytes::Write(isolate, data, length, string, enc);
316
141
    CHECK(actual <= length);
317
318
141
    if (actual == 0) {
319
1
      free(data);
320
1
      data = nullptr;
321
140
    } else if (actual < length) {
322
      data = node::Realloc(data, actual);
323
    }
324
  }
325
326
282
  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
3222
MaybeLocal<Object> New(Environment* env, size_t length) {
345
3222
  EscapableHandleScope scope(env->isolate());
346
347
  // V8 currently only allows a maximum Typed Array index of max Smi.
348
3222
  if (length > kMaxLength) {
349
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
350
    return Local<Object>();
351
  }
352
353
  return scope.EscapeMaybe(
354
6444
      AllocatedBuffer::AllocateManaged(env, length).ToBuffer());
355
}
356
357
358
2148
MaybeLocal<Object> Copy(Isolate* isolate, const char* data, size_t length) {
359
2148
  EscapableHandleScope handle_scope(isolate);
360
2148
  Environment* env = Environment::GetCurrent(isolate);
361
2148
  if (env == nullptr) {
362
1
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
363
    return MaybeLocal<Object>();
364
  }
365
  Local<Object> obj;
366
4294
  if (Buffer::Copy(env, data, length).ToLocal(&obj))
367
2147
    return handle_scope.Escape(obj);
368
  return Local<Object>();
369
}
370
371
372
12423
MaybeLocal<Object> Copy(Environment* env, const char* data, size_t length) {
373
12423
  EscapableHandleScope scope(env->isolate());
374
375
  // V8 currently only allows a maximum Typed Array index of max Smi.
376
12423
  if (length > kMaxLength) {
377
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
378
    return Local<Object>();
379
  }
380
381
24846
  AllocatedBuffer ret = AllocatedBuffer::AllocateManaged(env, length);
382
12423
  if (length > 0) {
383
12282
    memcpy(ret.data(), data, length);
384
  }
385
386
12423
  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
517
MaybeLocal<Object> New(Environment* env,
408
                       char* data,
409
                       size_t length,
410
                       FreeCallback callback,
411
                       void* hint) {
412
517
  EscapableHandleScope scope(env->isolate());
413
414
518
  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
518
      CallbackInfo::CreateTrackedArrayBuffer(env, data, length, callback, hint);
422
1552
  if (ab->SetPrivate(env->context(),
423
                     env->untransferable_object_private_symbol(),
424
1551
                     True(env->isolate())).IsNothing()) {
425
    return Local<Object>();
426
  }
427
517
  MaybeLocal<Uint8Array> ui = Buffer::New(env, ab, 0, length);
428
429
518
  if (ui.IsEmpty())
430
    return MaybeLocal<Object>();
431
432
518
  return scope.Escape(ui.ToLocalChecked());
433
}
434
435
// Warning: This function needs `data` to be allocated with malloc() and not
436
// necessarily isolate's ArrayBuffer::Allocator.
437
141
MaybeLocal<Object> New(Isolate* isolate, char* data, size_t length) {
438
141
  EscapableHandleScope handle_scope(isolate);
439
141
  Environment* env = Environment::GetCurrent(isolate);
440
141
  if (env == nullptr) {
441
    free(data);
442
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
443
    return MaybeLocal<Object>();
444
  }
445
  Local<Object> obj;
446
282
  if (Buffer::New(env, data, length).ToLocal(&obj))
447
141
    return handle_scope.Escape(obj);
448
  return Local<Object>();
449
}
450
451
// The contract for this function is that `data` is allocated with malloc()
452
// and not necessarily isolate's ArrayBuffer::Allocator.
453
488
MaybeLocal<Object> New(Environment* env,
454
                       char* data,
455
                       size_t length) {
456
488
  if (length > 0) {
457
488
    CHECK_NOT_NULL(data);
458
488
    CHECK(length <= kMaxLength);
459
  }
460
461
1457
  auto free_callback = [](char* data, void* hint) { free(data); };
462
488
  return New(env, data, length, free_callback, nullptr);
463
}
464
465
namespace {
466
467
141
void CreateFromString(const FunctionCallbackInfo<Value>& args) {
468
423
  CHECK(args[0]->IsString());
469
282
  CHECK(args[1]->IsInt32());
470
471
423
  enum encoding enc = static_cast<enum encoding>(args[1].As<Int32>()->Value());
472
  Local<Object> buf;
473
423
  if (New(args.GetIsolate(), args[0].As<String>(), enc).ToLocal(&buf))
474
282
    args.GetReturnValue().Set(buf);
475
141
}
476
477
478
template <encoding encoding>
479
432105
void StringSlice(const FunctionCallbackInfo<Value>& args) {
480
432105
  Environment* env = Environment::GetCurrent(args);
481
432105
  Isolate* isolate = env->isolate();
482
483



432290
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
484
432105
  ArrayBufferViewContents<char> buffer(args.This());
485
486



432105
  if (buffer.length() == 0)
487
356
    return args.GetReturnValue().SetEmptyString();
488
489
431927
  size_t start = 0;
490
431927
  size_t end = 0;
491






1727708
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[0], 0, &start));
492






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



431927
  if (end < start) end = start;
494






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



431927
  if (ret.IsEmpty()) {
505



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

91
  SPREAD_BUFFER_ARG(target_obj, target);
522
523
13
  size_t target_start = 0;
524
13
  size_t source_start = 0;
525
13
  size_t source_end = 0;
526
527

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

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

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

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

1423
  SPREAD_BUFFER_ARG(args[0], ts_obj);
558
559
  size_t start;
560

644
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &start));
561
  size_t end;
562

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

159
  if (start > end || fill_length + start > ts_obj_length)
571
    return args.GetReturnValue().Set(-2);
572
573
  // First check if Buffer has been passed.
574
159
  if (Buffer::HasInstance(args[1])) {
575

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



497894
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
654









4480996
  SPREAD_BUFFER_ARG(args.This(), ts_obj);
655
656



1493667
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "argument");
657
658
1991556
  Local<String> str = args[0]->ToString(env->context()).ToLocalChecked();
659
660
  size_t offset;
661
  size_t max_length;
662
663






1991556
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], 0, &offset));
664



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






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



497889
  if (max_length == 0)
675
10
    return args.GetReturnValue().Set(0);
676
677
1493652
  uint32_t written = StringBytes::Write(env->isolate(),
678
497884
                                        ts_obj_data + offset,
679
                                        max_length,
680
                                        str,
681
                                        encoding,
682
497884
                                        nullptr);
683



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

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

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

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

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

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

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

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

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

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

4093
  if (opt_offset <= -1 || buffer.length() == 0) {
1014
8
    return args.GetReturnValue().Set(-1);
1015
  }
1016
4089
  size_t offset = static_cast<size_t>(opt_offset);
1017
4089
  CHECK_LT(offset, buffer.length());
1018
1019
  const void* ptr;
1020
4089
  if (is_forward) {
1021
4081
    ptr = memchr(buffer.data() + offset, needle, buffer.length() - offset);
1022
  } else {
1023
8
    ptr = node::stringsearch::MemrchrFill(buffer.data(), needle, offset + 1);
1024
  }
1025
4089
  const char* ptr_char = static_cast<const char*>(ptr);
1026
12267
  args.GetReturnValue().Set(ptr ? static_cast<int>(ptr_char - buffer.data())
1027
                                : -1);
1028
}
1029
1030
1031
2
void Swap16(const FunctionCallbackInfo<Value>& args) {
1032
2
  Environment* env = Environment::GetCurrent(args);
1033
2
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1034

18
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1035
2
  SwapBytes16(ts_obj_data, ts_obj_length);
1036
4
  args.GetReturnValue().Set(args[0]);
1037
}
1038
1039
1040
2
void Swap32(const FunctionCallbackInfo<Value>& args) {
1041
2
  Environment* env = Environment::GetCurrent(args);
1042
2
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1043

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

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

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