GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: util.h Lines: 132 132 100.0 %
Date: 2022-05-16 04:15:04 Branches: 34 46 73.9 %

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
#ifndef SRC_UTIL_H_
23
#define SRC_UTIL_H_
24
25
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
26
27
#include "v8.h"
28
29
#include "node.h"
30
31
#include <climits>
32
#include <cstddef>
33
#include <cstdio>
34
#include <cstdlib>
35
#include <cstring>
36
37
#include <array>
38
#include <limits>
39
#include <memory>
40
#include <string>
41
#include <string_view>
42
#include <type_traits>
43
#include <set>
44
#include <unordered_map>
45
#include <utility>
46
#include <vector>
47
48
#ifdef __GNUC__
49
#define MUST_USE_RESULT __attribute__((warn_unused_result))
50
#else
51
#define MUST_USE_RESULT
52
#endif
53
54
namespace node {
55
56
// Maybe remove kPathSeparator when cpp17 is ready
57
#ifdef _WIN32
58
    constexpr char kPathSeparator = '\\';
59
/* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
60
#define PATH_MAX_BYTES (MAX_PATH * 4)
61
#else
62
    constexpr char kPathSeparator = '/';
63
#define PATH_MAX_BYTES (PATH_MAX)
64
#endif
65
66
// These should be used in our code as opposed to the native
67
// versions as they abstract out some platform and or
68
// compiler version specific functionality
69
// malloc(0) and realloc(ptr, 0) have implementation-defined behavior in
70
// that the standard allows them to either return a unique pointer or a
71
// nullptr for zero-sized allocation requests.  Normalize by always using
72
// a nullptr.
73
template <typename T>
74
inline T* UncheckedRealloc(T* pointer, size_t n);
75
template <typename T>
76
inline T* UncheckedMalloc(size_t n);
77
template <typename T>
78
inline T* UncheckedCalloc(size_t n);
79
80
// Same things, but aborts immediately instead of returning nullptr when
81
// no memory is available.
82
template <typename T>
83
inline T* Realloc(T* pointer, size_t n);
84
template <typename T>
85
inline T* Malloc(size_t n);
86
template <typename T>
87
inline T* Calloc(size_t n);
88
89
inline char* Malloc(size_t n);
90
inline char* Calloc(size_t n);
91
inline char* UncheckedMalloc(size_t n);
92
inline char* UncheckedCalloc(size_t n);
93
94
template <typename T>
95
inline T MultiplyWithOverflowCheck(T a, T b);
96
97
namespace per_process {
98
// Tells whether the per-process V8::Initialize() is called and
99
// if it is safe to call v8::Isolate::TryGetCurrent().
100
extern bool v8_initialized;
101
}  // namespace per_process
102
103
// Used by the allocation functions when allocation fails.
104
// Thin wrapper around v8::Isolate::LowMemoryNotification() that checks
105
// whether V8 is initialized.
106
void LowMemoryNotification();
107
108
// The reason that Assert() takes a struct argument instead of individual
109
// const char*s is to ease instruction cache pressure in calls from CHECK.
110
struct AssertionInfo {
111
  const char* file_line;  // filename:line
112
  const char* message;
113
  const char* function;
114
};
115
[[noreturn]] void NODE_EXTERN_PRIVATE Assert(const AssertionInfo& info);
116
[[noreturn]] void NODE_EXTERN_PRIVATE Abort();
117
void DumpBacktrace(FILE* fp);
118
119
// Windows 8+ does not like abort() in Release mode
120
#ifdef _WIN32
121
#define ABORT_NO_BACKTRACE() _exit(134)
122
#else
123
#define ABORT_NO_BACKTRACE() abort()
124
#endif
125
126
#define ABORT() node::Abort()
127
128
#define ERROR_AND_ABORT(expr)                                                 \
129
  do {                                                                        \
130
    /* Make sure that this struct does not end up in inline code, but      */ \
131
    /* rather in a read-only data section when modifying this code.        */ \
132
    static const node::AssertionInfo args = {                                 \
133
      __FILE__ ":" STRINGIFY(__LINE__), #expr, PRETTY_FUNCTION_NAME           \
134
    };                                                                        \
135
    node::Assert(args);                                                       \
136
  } while (0)
137
138
#ifdef __GNUC__
139
#define LIKELY(expr) __builtin_expect(!!(expr), 1)
140
#define UNLIKELY(expr) __builtin_expect(!!(expr), 0)
141
#define PRETTY_FUNCTION_NAME __PRETTY_FUNCTION__
142
#else
143
#define LIKELY(expr) expr
144
#define UNLIKELY(expr) expr
145
#define PRETTY_FUNCTION_NAME ""
146
#endif
147
148
#define STRINGIFY_(x) #x
149
#define STRINGIFY(x) STRINGIFY_(x)
150
151
#define CHECK(expr)                                                           \
152
  do {                                                                        \
153
    if (UNLIKELY(!(expr))) {                                                  \
154
      ERROR_AND_ABORT(expr);                                                  \
155
    }                                                                         \
156
  } while (0)
157
158
#define CHECK_EQ(a, b) CHECK((a) == (b))
159
#define CHECK_GE(a, b) CHECK((a) >= (b))
160
#define CHECK_GT(a, b) CHECK((a) > (b))
161
#define CHECK_LE(a, b) CHECK((a) <= (b))
162
#define CHECK_LT(a, b) CHECK((a) < (b))
163
#define CHECK_NE(a, b) CHECK((a) != (b))
164
#define CHECK_NULL(val) CHECK((val) == nullptr)
165
#define CHECK_NOT_NULL(val) CHECK((val) != nullptr)
166
#define CHECK_IMPLIES(a, b) CHECK(!(a) || (b))
167
168
#ifdef DEBUG
169
  #define DCHECK(expr) CHECK(expr)
170
  #define DCHECK_EQ(a, b) CHECK((a) == (b))
171
  #define DCHECK_GE(a, b) CHECK((a) >= (b))
172
  #define DCHECK_GT(a, b) CHECK((a) > (b))
173
  #define DCHECK_LE(a, b) CHECK((a) <= (b))
174
  #define DCHECK_LT(a, b) CHECK((a) < (b))
175
  #define DCHECK_NE(a, b) CHECK((a) != (b))
176
  #define DCHECK_NULL(val) CHECK((val) == nullptr)
177
  #define DCHECK_NOT_NULL(val) CHECK((val) != nullptr)
178
  #define DCHECK_IMPLIES(a, b) CHECK(!(a) || (b))
179
#else
180
  #define DCHECK(expr)
181
  #define DCHECK_EQ(a, b)
182
  #define DCHECK_GE(a, b)
183
  #define DCHECK_GT(a, b)
184
  #define DCHECK_LE(a, b)
185
  #define DCHECK_LT(a, b)
186
  #define DCHECK_NE(a, b)
187
  #define DCHECK_NULL(val)
188
  #define DCHECK_NOT_NULL(val)
189
  #define DCHECK_IMPLIES(a, b)
190
#endif
191
192
193
#define UNREACHABLE(...)                                                      \
194
  ERROR_AND_ABORT("Unreachable code reached" __VA_OPT__(": ") __VA_ARGS__)
195
196
// ECMA262 20.1.2.6 Number.MAX_SAFE_INTEGER (2^53-1)
197
constexpr int64_t kMaxSafeJsInteger = 9007199254740991;
198
199
inline bool IsSafeJsInt(v8::Local<v8::Value> v);
200
201
// TAILQ-style intrusive list node.
202
template <typename T>
203
class ListNode;
204
205
// TAILQ-style intrusive list head.
206
template <typename T, ListNode<T> (T::*M)>
207
class ListHead;
208
209
template <typename T>
210
class ListNode {
211
 public:
212
  inline ListNode();
213
  inline ~ListNode();
214
  inline void Remove();
215
  inline bool IsEmpty() const;
216
217
  ListNode(const ListNode&) = delete;
218
  ListNode& operator=(const ListNode&) = delete;
219
220
 private:
221
  template <typename U, ListNode<U> (U::*M)> friend class ListHead;
222
  friend int GenDebugSymbols();
223
  ListNode* prev_;
224
  ListNode* next_;
225
};
226
227
template <typename T, ListNode<T> (T::*M)>
228
class ListHead {
229
 public:
230
  class Iterator {
231
   public:
232
    inline T* operator*() const;
233
    inline const Iterator& operator++();
234
    inline bool operator!=(const Iterator& that) const;
235
236
   private:
237
    friend class ListHead;
238
    inline explicit Iterator(ListNode<T>* node);
239
    ListNode<T>* node_;
240
  };
241
242
24129
  inline ListHead() = default;
243
  inline ~ListHead();
244
  inline void PushBack(T* element);
245
  inline void PushFront(T* element);
246
  inline bool IsEmpty() const;
247
  inline T* PopFront();
248
  inline Iterator begin() const;
249
  inline Iterator end() const;
250
251
  ListHead(const ListHead&) = delete;
252
  ListHead& operator=(const ListHead&) = delete;
253
254
 private:
255
  friend int GenDebugSymbols();
256
  ListNode<T> head_;
257
};
258
259
// The helper is for doing safe downcasts from base types to derived types.
260
template <typename Inner, typename Outer>
261
class ContainerOfHelper {
262
 public:
263
  inline ContainerOfHelper(Inner Outer::*field, Inner* pointer);
264
  template <typename TypeName>
265
  inline operator TypeName*() const;
266
 private:
267
  Outer* const pointer_;
268
};
269
270
// Calculate the address of the outer (i.e. embedding) struct from
271
// the interior pointer to a data member.
272
template <typename Inner, typename Outer>
273
constexpr ContainerOfHelper<Inner, Outer> ContainerOf(Inner Outer::*field,
274
                                                      Inner* pointer);
275
276
// Convenience wrapper around v8::String::NewFromOneByte().
277
inline v8::Local<v8::String> OneByteString(v8::Isolate* isolate,
278
                                           const char* data,
279
                                           int length = -1);
280
281
// For the people that compile with -funsigned-char.
282
inline v8::Local<v8::String> OneByteString(v8::Isolate* isolate,
283
                                           const signed char* data,
284
                                           int length = -1);
285
286
inline v8::Local<v8::String> OneByteString(v8::Isolate* isolate,
287
                                           const unsigned char* data,
288
                                           int length = -1);
289
290
// Used to be a macro, hence the uppercase name.
291
template <int N>
292
6001079
inline v8::Local<v8::String> FIXED_ONE_BYTE_STRING(
293
    v8::Isolate* isolate,
294
    const char(&data)[N]) {
295
6001079
  return OneByteString(isolate, data, N - 1);
296
}
297
298
template <std::size_t N>
299
580
inline v8::Local<v8::String> FIXED_ONE_BYTE_STRING(
300
    v8::Isolate* isolate,
301
    const std::array<char, N>& arr) {
302
580
  return OneByteString(isolate, arr.data(), N - 1);
303
}
304
305
306
307
// Swaps bytes in place. nbytes is the number of bytes to swap and must be a
308
// multiple of the word size (checked by function).
309
inline void SwapBytes16(char* data, size_t nbytes);
310
inline void SwapBytes32(char* data, size_t nbytes);
311
inline void SwapBytes64(char* data, size_t nbytes);
312
313
// tolower() is locale-sensitive.  Use ToLower() instead.
314
inline char ToLower(char c);
315
inline std::string ToLower(const std::string& in);
316
317
// toupper() is locale-sensitive.  Use ToUpper() instead.
318
inline char ToUpper(char c);
319
inline std::string ToUpper(const std::string& in);
320
321
// strcasecmp() is locale-sensitive.  Use StringEqualNoCase() instead.
322
inline bool StringEqualNoCase(const char* a, const char* b);
323
324
// strncasecmp() is locale-sensitive.  Use StringEqualNoCaseN() instead.
325
inline bool StringEqualNoCaseN(const char* a, const char* b, size_t length);
326
327
template <typename T, size_t N>
328
11304633
constexpr size_t arraysize(const T (&)[N]) {
329
11304633
  return N;
330
}
331
332
template <typename T, size_t N>
333
constexpr size_t strsize(const T (&)[N]) {
334
  return N - 1;
335
}
336
337
// Allocates an array of member type T. For up to kStackStorageSize items,
338
// the stack is used, otherwise malloc().
339
template <typename T, size_t kStackStorageSize = 1024>
340
class MaybeStackBuffer {
341
 public:
342
5798
  const T* out() const {
343
5798
    return buf_;
344
  }
345
346
6189176
  T* out() {
347
6189176
    return buf_;
348
  }
349
350
  // operator* for compatibility with `v8::String::(Utf8)Value`
351
9251759
  T* operator*() {
352
9251759
    return buf_;
353
  }
354
355
32816
  const T* operator*() const {
356
32816
    return buf_;
357
  }
358
359
4334161
  T& operator[](size_t index) {
360
4334161
    CHECK_LT(index, length());
361
4334161
    return buf_[index];
362
  }
363
364
11251
  const T& operator[](size_t index) const {
365
11251
    CHECK_LT(index, length());
366
11251
    return buf_[index];
367
  }
368
369
12663378
  size_t length() const {
370
12663378
    return length_;
371
  }
372
373
  // Current maximum capacity of the buffer with which SetLength() can be used
374
  // without first calling AllocateSufficientStorage().
375
19321246
  size_t capacity() const {
376
19321246
    return capacity_;
377
  }
378
379
  // Make sure enough space for `storage` entries is available.
380
  // This method can be called multiple times throughout the lifetime of the
381
  // buffer, but once this has been called Invalidate() cannot be used.
382
  // Content of the buffer in the range [0, length()) is preserved.
383
6882720
  void AllocateSufficientStorage(size_t storage) {
384
6882720
    CHECK(!IsInvalidated());
385
6882720
    if (storage > capacity()) {
386
276621
      bool was_allocated = IsAllocated();
387
276621
      T* allocated_ptr = was_allocated ? buf_ : nullptr;
388
276621
      buf_ = Realloc(allocated_ptr, storage);
389
276621
      capacity_ = storage;
390

276621
      if (!was_allocated && length_ > 0)
391
4
        memcpy(buf_, buf_st_, length_ * sizeof(buf_[0]));
392
    }
393
394
6882720
    length_ = storage;
395
6882720
  }
396
397
6084978
  void SetLength(size_t length) {
398
    // capacity() returns how much memory is actually available.
399
6084978
    CHECK_LE(length, capacity());
400
6084978
    length_ = length;
401
6084978
  }
402
403
8940177
  void SetLengthAndZeroTerminate(size_t length) {
404
    // capacity() returns how much memory is actually available.
405
8940177
    CHECK_LE(length + 1, capacity());
406
8940177
    SetLength(length);
407
408
    // T() is 0 for integer types, nullptr for pointers, etc.
409
8940177
    buf_[length] = T();
410
8940177
  }
411
412
  // Make dereferencing this object return nullptr.
413
  // This method can be called multiple times throughout the lifetime of the
414
  // buffer, but once this has been called AllocateSufficientStorage() cannot
415
  // be used.
416
2
  void Invalidate() {
417
2
    CHECK(!IsAllocated());
418
2
    capacity_ = 0;
419
2
    length_ = 0;
420
2
    buf_ = nullptr;
421
2
  }
422
423
  // If the buffer is stored in the heap rather than on the stack.
424
8824213
  bool IsAllocated() const {
425

8824213
    return !IsInvalidated() && buf_ != buf_st_;
426
  }
427
428
  // If Invalidate() has been called.
429
15765720
  bool IsInvalidated() const {
430
15765720
    return buf_ == nullptr;
431
  }
432
433
  // Release ownership of the malloc'd buffer.
434
  // Note: This does not free the buffer.
435
630
  void Release() {
436
630
    CHECK(IsAllocated());
437
630
    buf_ = buf_st_;
438
630
    length_ = 0;
439
630
    capacity_ = arraysize(buf_st_);
440
630
  }
441
442
8439476
  MaybeStackBuffer()
443
149442084
      : length_(0), capacity_(arraysize(buf_st_)), buf_(buf_st_) {
444
    // Default to a zero-length, null-terminated buffer.
445
8439476
    buf_[0] = T();
446
8439476
  }
447
448
799848
  explicit MaybeStackBuffer(size_t storage) : MaybeStackBuffer() {
449
799848
    AllocateSufficientStorage(storage);
450
799848
  }
451
452
8538764
  ~MaybeStackBuffer() {
453
8538764
    if (IsAllocated())
454
275984
      free(buf_);
455
8538764
  }
456
457
 private:
458
  size_t length_;
459
  // capacity of the malloc'ed buf_
460
  size_t capacity_;
461
  T* buf_;
462
  T buf_st_[kStackStorageSize];
463
};
464
465
// Provides access to an ArrayBufferView's storage, either the original,
466
// or for small data, a copy of it. This object's lifetime is bound to the
467
// original ArrayBufferView's lifetime.
468
template <typename T, size_t kStackStorageSize = 64>
469
class ArrayBufferViewContents {
470
 public:
471
1230
  ArrayBufferViewContents() = default;
472
473
  explicit inline ArrayBufferViewContents(v8::Local<v8::Value> value);
474
  explicit inline ArrayBufferViewContents(v8::Local<v8::Object> value);
475
  explicit inline ArrayBufferViewContents(v8::Local<v8::ArrayBufferView> abv);
476
  inline void Read(v8::Local<v8::ArrayBufferView> abv);
477
478
184247
  inline const T* data() const { return data_; }
479
464860
  inline size_t length() const { return length_; }
480
481
 private:
482
  T stack_storage_[kStackStorageSize];
483
  T* data_ = nullptr;
484
  size_t length_ = 0;
485
};
486
487
class Utf8Value : public MaybeStackBuffer<char> {
488
 public:
489
  explicit Utf8Value(v8::Isolate* isolate, v8::Local<v8::Value> value);
490
491
984
  inline std::string ToString() const { return std::string(out(), length()); }
492
493
4814
  inline bool operator==(const char* a) const {
494
4814
    return strcmp(out(), a) == 0;
495
  }
496
};
497
498
class TwoByteValue : public MaybeStackBuffer<uint16_t> {
499
 public:
500
  explicit TwoByteValue(v8::Isolate* isolate, v8::Local<v8::Value> value);
501
};
502
503
class BufferValue : public MaybeStackBuffer<char> {
504
 public:
505
  explicit BufferValue(v8::Isolate* isolate, v8::Local<v8::Value> value);
506
507
  inline std::string ToString() const { return std::string(out(), length()); }
508
};
509
510
#define SPREAD_BUFFER_ARG(val, name)                                          \
511
  CHECK((val)->IsArrayBufferView());                                          \
512
  v8::Local<v8::ArrayBufferView> name = (val).As<v8::ArrayBufferView>();      \
513
  std::shared_ptr<v8::BackingStore> name##_bs =                               \
514
      name->Buffer()->GetBackingStore();                                      \
515
  const size_t name##_offset = name->ByteOffset();                            \
516
  const size_t name##_length = name->ByteLength();                            \
517
  char* const name##_data =                                                   \
518
      static_cast<char*>(name##_bs->Data()) + name##_offset;                  \
519
  if (name##_length > 0)                                                      \
520
    CHECK_NE(name##_data, nullptr);
521
522
// Use this when a variable or parameter is unused in order to explicitly
523
// silence a compiler warning about that.
524
4905548
template <typename T> inline void USE(T&&) {}
525
526
template <typename Fn>
527
struct OnScopeLeaveImpl {
528
  Fn fn_;
529
  bool active_;
530
531
3253728
  explicit OnScopeLeaveImpl(Fn&& fn) : fn_(std::move(fn)), active_(true) {}
532
1640579
  ~OnScopeLeaveImpl() { if (active_) fn_(); }
533
534
  OnScopeLeaveImpl(const OnScopeLeaveImpl& other) = delete;
535
  OnScopeLeaveImpl& operator=(const OnScopeLeaveImpl& other) = delete;
536
  OnScopeLeaveImpl(OnScopeLeaveImpl&& other)
537
    : fn_(std::move(other.fn_)), active_(other.active_) {
538
    other.active_ = false;
539
  }
540
  OnScopeLeaveImpl& operator=(OnScopeLeaveImpl&& other) {
541
    if (this == &other) return *this;
542
    this->~OnScopeLeave();
543
    new (this)OnScopeLeaveImpl(std::move(other));
544
    return *this;
545
  }
546
};
547
548
// Run a function when exiting the current scope. Used like this:
549
// auto on_scope_leave = OnScopeLeave([&] {
550
//   // ... run some code ...
551
// });
552
template <typename Fn>
553
3253728
inline MUST_USE_RESULT OnScopeLeaveImpl<Fn> OnScopeLeave(Fn&& fn) {
554
3253728
  return OnScopeLeaveImpl<Fn>{std::move(fn)};
555
}
556
557
// Simple RAII wrapper for contiguous data that uses malloc()/free().
558
template <typename T>
559
struct MallocedBuffer {
560
  T* data;
561
  size_t size;
562
563
  T* release() {
564
    T* ret = data;
565
    data = nullptr;
566
    return ret;
567
  }
568
569
  void Truncate(size_t new_size) {
570
    CHECK(new_size <= size);
571
    size = new_size;
572
  }
573
574
  void Realloc(size_t new_size) {
575
    Truncate(new_size);
576
    data = UncheckedRealloc(data, new_size);
577
  }
578
579
61908
  inline bool is_empty() const { return data == nullptr; }
580
581
98578
  MallocedBuffer() : data(nullptr), size(0) {}
582
23
  explicit MallocedBuffer(size_t size) : data(Malloc<T>(size)), size(size) {}
583
61921
  MallocedBuffer(T* data, size_t size) : data(data), size(size) {}
584
160463
  MallocedBuffer(MallocedBuffer&& other) : data(other.data), size(other.size) {
585
160463
    other.data = nullptr;
586
160463
  }
587
61935
  MallocedBuffer& operator=(MallocedBuffer&& other) {
588
61935
    this->~MallocedBuffer();
589
61935
    return *new(this) MallocedBuffer(std::move(other));
590
  }
591
320942
  ~MallocedBuffer() {
592
320942
    free(data);
593
320942
  }
594
  MallocedBuffer(const MallocedBuffer&) = delete;
595
  MallocedBuffer& operator=(const MallocedBuffer&) = delete;
596
};
597
598
template <typename T>
599
class NonCopyableMaybe {
600
 public:
601
4030
  NonCopyableMaybe() : empty_(true) {}
602
3804
  explicit NonCopyableMaybe(T&& value)
603
      : empty_(false),
604
7608
        value_(std::move(value)) {}
605
606
7556
  bool IsEmpty() const {
607
7556
    return empty_;
608
  }
609
610
1473
  const T* get() const {
611
1473
    return empty_ ? nullptr : &value_;
612
  }
613
614
24
  const T* operator->() const {
615
24
    CHECK(!empty_);
616
24
    return &value_;
617
  }
618
619
3709
  T&& Release() {
620
3709
    CHECK_EQ(empty_, false);
621
3709
    empty_ = true;
622
3709
    return std::move(value_);
623
  }
624
625
 private:
626
  bool empty_;
627
  T value_;
628
};
629
630
// Test whether some value can be called with ().
631
template <typename T, typename = void>
632
struct is_callable : std::is_function<T> { };
633
634
template <typename T>
635
struct is_callable<T, typename std::enable_if<
636
    std::is_same<decltype(void(&T::operator())), void>::value
637
    >::type> : std::true_type { };
638
639
template <typename T, void (*function)(T*)>
640
struct FunctionDeleter {
641
184810
  void operator()(T* pointer) const { function(pointer); }
642
  typedef std::unique_ptr<T, FunctionDeleter> Pointer;
643
};
644
645
template <typename T, void (*function)(T*)>
646
using DeleteFnPtr = typename FunctionDeleter<T, function>::Pointer;
647
648
std::vector<std::string> SplitString(const std::string& in, char delim);
649
650
inline v8::MaybeLocal<v8::Value> ToV8Value(v8::Local<v8::Context> context,
651
                                           std::string_view str,
652
                                           v8::Isolate* isolate = nullptr);
653
template <typename T, typename test_for_number =
654
    typename std::enable_if<std::numeric_limits<T>::is_specialized, bool>::type>
655
inline v8::MaybeLocal<v8::Value> ToV8Value(v8::Local<v8::Context> context,
656
                                           const T& number,
657
                                           v8::Isolate* isolate = nullptr);
658
template <typename T>
659
inline v8::MaybeLocal<v8::Value> ToV8Value(v8::Local<v8::Context> context,
660
                                           const std::vector<T>& vec,
661
                                           v8::Isolate* isolate = nullptr);
662
template <typename T>
663
inline v8::MaybeLocal<v8::Value> ToV8Value(v8::Local<v8::Context> context,
664
                                           const std::set<T>& set,
665
                                           v8::Isolate* isolate = nullptr);
666
template <typename T, typename U>
667
inline v8::MaybeLocal<v8::Value> ToV8Value(v8::Local<v8::Context> context,
668
                                           const std::unordered_map<T, U>& map,
669
                                           v8::Isolate* isolate = nullptr);
670
671
// These macros expects a `Isolate* isolate` and a `Local<Context> context`
672
// to be in the scope.
673
#define READONLY_PROPERTY(obj, name, value)                                    \
674
  do {                                                                         \
675
    obj->DefineOwnProperty(                                                    \
676
           context, FIXED_ONE_BYTE_STRING(isolate, name), value, v8::ReadOnly) \
677
        .Check();                                                              \
678
  } while (0)
679
680
#define READONLY_DONT_ENUM_PROPERTY(obj, name, var)                            \
681
  do {                                                                         \
682
    obj->DefineOwnProperty(                                                    \
683
           context,                                                            \
684
           OneByteString(isolate, name),                                       \
685
           var,                                                                \
686
           static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontEnum))    \
687
        .Check();                                                              \
688
  } while (0)
689
690
#define READONLY_FALSE_PROPERTY(obj, name)                                     \
691
  READONLY_PROPERTY(obj, name, v8::False(isolate))
692
693
#define READONLY_TRUE_PROPERTY(obj, name)                                      \
694
  READONLY_PROPERTY(obj, name, v8::True(isolate))
695
696
#define READONLY_STRING_PROPERTY(obj, name, str)                               \
697
  READONLY_PROPERTY(obj, name, ToV8Value(context, str).ToLocalChecked())
698
699
// Variation on NODE_DEFINE_CONSTANT that sets a String value.
700
#define NODE_DEFINE_STRING_CONSTANT(target, name, constant)                    \
701
  do {                                                                         \
702
    v8::Isolate* isolate = target->GetIsolate();                               \
703
    v8::Local<v8::String> constant_name =                                      \
704
        v8::String::NewFromUtf8(isolate, name).ToLocalChecked();               \
705
    v8::Local<v8::String> constant_value =                                     \
706
        v8::String::NewFromUtf8(isolate, constant).ToLocalChecked();           \
707
    v8::PropertyAttribute constant_attributes =                                \
708
        static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete);     \
709
    target                                                                     \
710
        ->DefineOwnProperty(isolate->GetCurrentContext(),                      \
711
                            constant_name,                                     \
712
                            constant_value,                                    \
713
                            constant_attributes)                               \
714
        .Check();                                                              \
715
  } while (0)
716
717
enum Endianness {
718
  kLittleEndian,  // _Not_ LITTLE_ENDIAN, clashes with endian.h.
719
  kBigEndian
720
};
721
722
8401
inline enum Endianness GetEndianness() {
723
  // Constant-folded by the compiler.
724
  const union {
725
    uint8_t u8[2];
726
    uint16_t u16;
727
8401
  } u = {{1, 0}};
728
8401
  return u.u16 == 1 ? kLittleEndian : kBigEndian;
729
}
730
731
1
inline bool IsLittleEndian() {
732
1
  return GetEndianness() == kLittleEndian;
733
}
734
735
8400
inline bool IsBigEndian() {
736
8400
  return GetEndianness() == kBigEndian;
737
}
738
739
// Round up a to the next highest multiple of b.
740
template <typename T>
741
161207
constexpr T RoundUp(T a, T b) {
742
161207
  return a % b != 0 ? a + b - (a % b) : a;
743
}
744
745
// Align ptr to an `alignment`-bytes boundary.
746
template <typename T, typename U>
747
26031
constexpr T* AlignUp(T* ptr, U alignment) {
748
  return reinterpret_cast<T*>(
749
26031
      RoundUp(reinterpret_cast<uintptr_t>(ptr), alignment));
750
}
751
752
class SlicedArguments : public MaybeStackBuffer<v8::Local<v8::Value>> {
753
 public:
754
  inline explicit SlicedArguments(
755
      const v8::FunctionCallbackInfo<v8::Value>& args, size_t start = 0);
756
};
757
758
// Convert a v8::PersistentBase, e.g. v8::Global, to a Local, with an extra
759
// optimization for strong persistent handles.
760
class PersistentToLocal {
761
 public:
762
  // If persistent.IsWeak() == false, then do not call persistent.Reset()
763
  // while the returned Local<T> is still in scope, it will destroy the
764
  // reference to the object.
765
  template <class TypeName>
766
6735112
  static inline v8::Local<TypeName> Default(
767
      v8::Isolate* isolate,
768
      const v8::PersistentBase<TypeName>& persistent) {
769
6735112
    if (persistent.IsWeak()) {
770
4463076
      return PersistentToLocal::Weak(isolate, persistent);
771
    } else {
772
2272036
      return PersistentToLocal::Strong(persistent);
773
    }
774
  }
775
776
  // Unchecked conversion from a non-weak Persistent<T> to Local<T>,
777
  // use with care!
778
  //
779
  // Do not call persistent.Reset() while the returned Local<T> is still in
780
  // scope, it will destroy the reference to the object.
781
  template <class TypeName>
782
35762272
  static inline v8::Local<TypeName> Strong(
783
      const v8::PersistentBase<TypeName>& persistent) {
784
    DCHECK(!persistent.IsWeak());
785
    return *reinterpret_cast<v8::Local<TypeName>*>(
786
35762272
        const_cast<v8::PersistentBase<TypeName>*>(&persistent));
787
  }
788
789
  template <class TypeName>
790
2347384
  static inline v8::Local<TypeName> Weak(
791
      v8::Isolate* isolate,
792
      const v8::PersistentBase<TypeName>& persistent) {
793
2347384
    return v8::Local<TypeName>::New(isolate, persistent);
794
  }
795
};
796
797
// Can be used as a key for std::unordered_map when lookup performance is more
798
// important than size and the keys are statically used to avoid redundant hash
799
// computations.
800
class FastStringKey {
801
 public:
802
  constexpr explicit FastStringKey(const char* name);
803
804
  struct Hash {
805
    constexpr size_t operator()(const FastStringKey& key) const;
806
  };
807
  constexpr bool operator==(const FastStringKey& other) const;
808
809
  constexpr const char* c_str() const;
810
811
 private:
812
  static constexpr size_t HashImpl(const char* str);
813
814
  const char* name_;
815
  size_t cached_hash_;
816
};
817
818
// Like std::static_pointer_cast but for unique_ptr with the default deleter.
819
template <typename T, typename U>
820
10825
std::unique_ptr<T> static_unique_pointer_cast(std::unique_ptr<U>&& ptr) {
821
10825
  return std::unique_ptr<T>(static_cast<T*>(ptr.release()));
822
}
823
824
#define MAYBE_FIELD_PTR(ptr, field) ptr == nullptr ? nullptr : &(ptr->field)
825
826
// Returns a non-zero code if it fails to open or read the file,
827
// aborts if it fails to close the file.
828
int ReadFileSync(std::string* result, const char* path);
829
}  // namespace node
830
831
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
832
833
#endif  // SRC_UTIL_H_