GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/util.h Lines: 118 123 95.9 %
Date: 2019-07-28 22:34:34 Branches: 62 114 54.4 %

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

3133047
    CHECK_LT(index, length());
337
3133047
    return buf_[index];
338
  }
339
340
8
  const T& operator[](size_t index) const {
341
8
    CHECK_LT(index, length());
342
8
    return buf_[index];
343
  }
344
345
4437672
  size_t length() const {
346
4437672
    return length_;
347
  }
348
349
  // Current maximum capacity of the buffer with which SetLength() can be used
350
  // without first calling AllocateSufficientStorage().
351
17822016
  size_t capacity() const {
352
17822016
    return IsAllocated() ? capacity_ :
353




17822023
                           IsInvalidated() ? 0 : kStackStorageSize;
354
  }
355
356
  // Make sure enough space for `storage` entries is available.
357
  // This method can be called multiple times throughout the lifetime of the
358
  // buffer, but once this has been called Invalidate() cannot be used.
359
  // Content of the buffer in the range [0, length()) is preserved.
360
6356822
  void AllocateSufficientStorage(size_t storage) {
361


6356822
    CHECK(!IsInvalidated());
362


6356824
    if (storage > capacity()) {
363
413674
      bool was_allocated = IsAllocated();
364


413674
      T* allocated_ptr = was_allocated ? buf_ : nullptr;
365
413674
      buf_ = Realloc(allocated_ptr, storage);
366
413674
      capacity_ = storage;
367




413674
      if (!was_allocated && length_ > 0)
368
        memcpy(buf_, buf_st_, length_ * sizeof(buf_[0]));
369
    }
370
371
6356826
    length_ = storage;
372
6356826
  }
373
374
6011881
  void SetLength(size_t length) {
375
    // capacity() returns how much memory is actually available.
376

6011881
    CHECK_LE(length, capacity());
377
6011881
    length_ = length;
378
6011881
  }
379
380
5438235
  void SetLengthAndZeroTerminate(size_t length) {
381
    // capacity() returns how much memory is actually available.
382

5438235
    CHECK_LE(length + 1, capacity());
383
5438240
    SetLength(length);
384
385
    // T() is 0 for integer types, nullptr for pointers, etc.
386
5438238
    buf_[length] = T();
387
5438238
  }
388
389
  // Make derefencing this object return nullptr.
390
  // This method can be called multiple times throughout the lifetime of the
391
  // buffer, but once this has been called AllocateSufficientStorage() cannot
392
  // be used.
393
  void Invalidate() {
394
    CHECK(!IsAllocated());
395
    length_ = 0;
396
    buf_ = nullptr;
397
  }
398
399
  // If the buffer is stored in the heap rather than on the stack.
400
24666471
  bool IsAllocated() const {
401




24666471
    return !IsInvalidated() && buf_ != buf_st_;
402
  }
403
404
  // If Invalidate() has been called.
405
48424560
  bool IsInvalidated() const {
406
48424560
    return buf_ == nullptr;
407
  }
408
409
  // Release ownership of the malloc'd buffer.
410
  // Note: This does not free the buffer.
411
2
  void Release() {
412

2
    CHECK(IsAllocated());
413
2
    buf_ = buf_st_;
414
2
    length_ = 0;
415
2
    capacity_ = 0;
416
2
  }
417
418
261579400
  MaybeStackBuffer() : length_(0), capacity_(0), buf_(buf_st_) {
419
    // Default to a zero-length, null-terminated buffer.
420
6814914
    buf_[0] = T();
421
6429730
  }
422
423
231956
  explicit MaybeStackBuffer(size_t storage) : MaybeStackBuffer() {
424
231956
    AllocateSufficientStorage(storage);
425
231956
  }
426
427
6429721
  ~MaybeStackBuffer() {
428


6429721
    if (IsAllocated())
429
413672
      free(buf_);
430
6429723
  }
431
432
 private:
433
  size_t length_;
434
  // capacity of the malloc'ed buf_
435
  size_t capacity_;
436
  T* buf_;
437
  T buf_st_[kStackStorageSize];
438
};
439
440
// Provides access to an ArrayBufferView's storage, either the original,
441
// or for small data, a copy of it. This object's lifetime is bound to the
442
// original ArrayBufferView's lifetime.
443
template <typename T, size_t kStackStorageSize = 64>
444
class ArrayBufferViewContents {
445
 public:
446
1681
  ArrayBufferViewContents() = default;
447
448
  explicit inline ArrayBufferViewContents(v8::Local<v8::Value> value);
449
  explicit inline ArrayBufferViewContents(v8::Local<v8::Object> value);
450
  explicit inline ArrayBufferViewContents(v8::Local<v8::ArrayBufferView> abv);
451
  inline void Read(v8::Local<v8::ArrayBufferView> abv);
452
453
1883791
  inline const T* data() const { return data_; }
454
5621900
  inline size_t length() const { return length_; }
455
456
 private:
457
  T stack_storage_[kStackStorageSize];
458
  T* data_ = nullptr;
459
  size_t length_ = 0;
460
};
461
462
5192019
class Utf8Value : public MaybeStackBuffer<char> {
463
 public:
464
  explicit Utf8Value(v8::Isolate* isolate, v8::Local<v8::Value> value);
465
};
466
467
583
class TwoByteValue : public MaybeStackBuffer<uint16_t> {
468
 public:
469
  explicit TwoByteValue(v8::Isolate* isolate, v8::Local<v8::Value> value);
470
};
471
472
245947
class BufferValue : public MaybeStackBuffer<char> {
473
 public:
474
  explicit BufferValue(v8::Isolate* isolate, v8::Local<v8::Value> value);
475
};
476
477
#define SPREAD_BUFFER_ARG(val, name)                                          \
478
  CHECK((val)->IsArrayBufferView());                                          \
479
  v8::Local<v8::ArrayBufferView> name = (val).As<v8::ArrayBufferView>();      \
480
  v8::ArrayBuffer::Contents name##_c = name->Buffer()->GetContents();         \
481
  const size_t name##_offset = name->ByteOffset();                            \
482
  const size_t name##_length = name->ByteLength();                            \
483
  char* const name##_data =                                                   \
484
      static_cast<char*>(name##_c.Data()) + name##_offset;                    \
485
  if (name##_length > 0)                                                      \
486
    CHECK_NE(name##_data, nullptr);
487
488
// Use this when a variable or parameter is unused in order to explicitly
489
// silence a compiler warning about that.
490
73588
template <typename T> inline void USE(T&&) {}
491
492
// Run a function when exiting the current scope.
493
struct OnScopeLeave {
494
  std::function<void()> fn_;
495
496
120767
  explicit OnScopeLeave(std::function<void()> fn) : fn_(std::move(fn)) {}
497
120761
  ~OnScopeLeave() { fn_(); }
498
};
499
500
// Simple RAII wrapper for contiguous data that uses malloc()/free().
501
template <typename T>
502
struct MallocedBuffer {
503
  T* data;
504
  size_t size;
505
506
2
  T* release() {
507
2
    T* ret = data;
508
2
    data = nullptr;
509
2
    return ret;
510
  }
511
512
  void Truncate(size_t new_size) {
513
    CHECK(new_size <= size);
514
    size = new_size;
515
  }
516
517
37769
  inline bool is_empty() const { return data == nullptr; }
518
519
164737
  MallocedBuffer() : data(nullptr), size(0) {}
520
4
  explicit MallocedBuffer(size_t size) : data(Malloc<T>(size)), size(size) {}
521
37857
  MallocedBuffer(T* data, size_t size) : data(data), size(size) {}
522
350558
  MallocedBuffer(MallocedBuffer&& other) : data(other.data), size(other.size) {
523
350558
    other.data = nullptr;
524
350558
  }
525
85917
  MallocedBuffer& operator=(MallocedBuffer&& other) {
526
85917
    this->~MallocedBuffer();
527
85905
    return *new(this) MallocedBuffer(std::move(other));
528
  }
529
553018
  ~MallocedBuffer() {
530
553018
    free(data);
531
553018
  }
532
  MallocedBuffer(const MallocedBuffer&) = delete;
533
  MallocedBuffer& operator=(const MallocedBuffer&) = delete;
534
};
535
536
template <typename T>
537
1248
class NonCopyableMaybe {
538
 public:
539
1
  NonCopyableMaybe() : empty_(true) {}
540
1247
  explicit NonCopyableMaybe(T&& value)
541
      : empty_(false),
542
1247
        value_(std::move(value)) {}
543
544
1248
  bool IsEmpty() const {
545
1248
    return empty_;
546
  }
547
548
1247
  T&& Release() {
549
1247
    CHECK_EQ(empty_, false);
550
1247
    empty_ = true;
551
1247
    return std::move(value_);
552
  }
553
554
 private:
555
  bool empty_;
556
  T value_;
557
};
558
559
// Test whether some value can be called with ().
560
template <typename T, typename = void>
561
struct is_callable : std::is_function<T> { };
562
563
template <typename T>
564
struct is_callable<T, typename std::enable_if<
565
    std::is_same<decltype(void(&T::operator())), void>::value
566
    >::type> : std::true_type { };
567
568
template <typename T, void (*function)(T*)>
569
struct FunctionDeleter {
570
487183
  void operator()(T* pointer) const { function(pointer); }
571
  typedef std::unique_ptr<T, FunctionDeleter> Pointer;
572
};
573
574
template <typename T, void (*function)(T*)>
575
using DeleteFnPtr = typename FunctionDeleter<T, function>::Pointer;
576
577
std::vector<std::string> SplitString(const std::string& in, char delim);
578
579
inline v8::MaybeLocal<v8::Value> ToV8Value(v8::Local<v8::Context> context,
580
                                           const std::string& str,
581
                                           v8::Isolate* isolate = nullptr);
582
template <typename T, typename test_for_number =
583
    typename std::enable_if<std::numeric_limits<T>::is_specialized, bool>::type>
584
inline v8::MaybeLocal<v8::Value> ToV8Value(v8::Local<v8::Context> context,
585
                                           const T& number,
586
                                           v8::Isolate* isolate = nullptr);
587
template <typename T>
588
inline v8::MaybeLocal<v8::Value> ToV8Value(v8::Local<v8::Context> context,
589
                                           const std::vector<T>& vec,
590
                                           v8::Isolate* isolate = nullptr);
591
template <typename T, typename U>
592
inline v8::MaybeLocal<v8::Value> ToV8Value(v8::Local<v8::Context> context,
593
                                           const std::unordered_map<T, U>& map,
594
                                           v8::Isolate* isolate = nullptr);
595
596
// These macros expects a `Isolate* isolate` and a `Local<Context> context`
597
// to be in the scope.
598
#define READONLY_PROPERTY(obj, name, value)                                    \
599
  do {                                                                         \
600
    obj->DefineOwnProperty(                                                    \
601
           context, FIXED_ONE_BYTE_STRING(isolate, name), value, v8::ReadOnly) \
602
        .Check();                                                              \
603
  } while (0)
604
605
#define READONLY_DONT_ENUM_PROPERTY(obj, name, var)                            \
606
  do {                                                                         \
607
    obj->DefineOwnProperty(                                                    \
608
           context,                                                            \
609
           OneByteString(isolate, name),                                       \
610
           var,                                                                \
611
           static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontEnum))    \
612
        .Check();                                                              \
613
  } while (0)
614
615
#define READONLY_FALSE_PROPERTY(obj, name)                                     \
616
  READONLY_PROPERTY(obj, name, v8::False(isolate))
617
618
#define READONLY_TRUE_PROPERTY(obj, name)                                      \
619
  READONLY_PROPERTY(obj, name, v8::True(isolate))
620
621
#define READONLY_STRING_PROPERTY(obj, name, str)                               \
622
  READONLY_PROPERTY(obj, name, ToV8Value(context, str).ToLocalChecked())
623
624
// Variation on NODE_DEFINE_CONSTANT that sets a String value.
625
#define NODE_DEFINE_STRING_CONSTANT(target, name, constant)                    \
626
  do {                                                                         \
627
    v8::Isolate* isolate = target->GetIsolate();                               \
628
    v8::Local<v8::String> constant_name =                                      \
629
        v8::String::NewFromUtf8(isolate, name, v8::NewStringType::kNormal)     \
630
            .ToLocalChecked();                                                 \
631
    v8::Local<v8::String> constant_value =                                     \
632
        v8::String::NewFromUtf8(isolate, constant, v8::NewStringType::kNormal) \
633
            .ToLocalChecked();                                                 \
634
    v8::PropertyAttribute constant_attributes =                                \
635
        static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete);     \
636
    target                                                                     \
637
        ->DefineOwnProperty(isolate->GetCurrentContext(),                      \
638
                            constant_name,                                     \
639
                            constant_value,                                    \
640
                            constant_attributes)                               \
641
        .Check();                                                              \
642
  } while (0)
643
644
enum Endianness {
645
  kLittleEndian,  // _Not_ LITTLE_ENDIAN, clashes with endian.h.
646
  kBigEndian
647
};
648
649
8234
inline enum Endianness GetEndianness() {
650
  // Constant-folded by the compiler.
651
  const union {
652
    uint8_t u8[2];
653
    uint16_t u16;
654
8234
  } u = {{1, 0}};
655
8234
  return u.u16 == 1 ? kLittleEndian : kBigEndian;
656
}
657
658
1
inline bool IsLittleEndian() {
659
1
  return GetEndianness() == kLittleEndian;
660
}
661
662
8233
inline bool IsBigEndian() {
663
8233
  return GetEndianness() == kBigEndian;
664
}
665
666
template <typename T, size_t N>
667
2624659
constexpr size_t arraysize(const T (&)[N]) {
668
2624659
  return N;
669
}
670
671
// Round up a to the next highest multiple of b.
672
template <typename T>
673
871826
constexpr T RoundUp(T a, T b) {
674
871826
  return a % b != 0 ? a + b - (a % b) : a;
675
}
676
677
#ifdef __GNUC__
678
#define MUST_USE_RESULT __attribute__((warn_unused_result))
679
#else
680
#define MUST_USE_RESULT
681
#endif
682
683
229738
class SlicedArguments : public MaybeStackBuffer<v8::Local<v8::Value>> {
684
 public:
685
  inline explicit SlicedArguments(
686
      const v8::FunctionCallbackInfo<v8::Value>& args, size_t start = 0);
687
};
688
689
// Convert a v8::PersistentBase, e.g. v8::Global, to a Local, with an extra
690
// optimization for strong persistent handles.
691
class PersistentToLocal {
692
 public:
693
  // If persistent.IsWeak() == false, then do not call persistent.Reset()
694
  // while the returned Local<T> is still in scope, it will destroy the
695
  // reference to the object.
696
  template <class TypeName>
697
33358971
  static inline v8::Local<TypeName> Default(
698
      v8::Isolate* isolate,
699
      const v8::PersistentBase<TypeName>& persistent) {
700

33358971
    if (persistent.IsWeak()) {
701
30932969
      return PersistentToLocal::Weak(isolate, persistent);
702
    } else {
703
2426002
      return PersistentToLocal::Strong(persistent);
704
    }
705
  }
706
707
  // Unchecked conversion from a non-weak Persistent<T> to Local<T>,
708
  // use with care!
709
  //
710
  // Do not call persistent.Reset() while the returned Local<T> is still in
711
  // scope, it will destroy the reference to the object.
712
  template <class TypeName>
713
26407219
  static inline v8::Local<TypeName> Strong(
714
      const v8::PersistentBase<TypeName>& persistent) {
715
    return *reinterpret_cast<v8::Local<TypeName>*>(
716
26407219
        const_cast<v8::PersistentBase<TypeName>*>(&persistent));
717
  }
718
719
  template <class TypeName>
720
30932969
  static inline v8::Local<TypeName> Weak(
721
      v8::Isolate* isolate,
722
      const v8::PersistentBase<TypeName>& persistent) {
723
30932969
    return v8::Local<TypeName>::New(isolate, persistent);
724
  }
725
};
726
727
}  // namespace node
728
729
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
730
731
#endif  // SRC_UTIL_H_