Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-09-13 09:14:39

0001 // Copyright 2021 the V8 project authors. All rights reserved.
0002 // Use of this source code is governed by a BSD-style license that can be
0003 // found in the LICENSE file.
0004 
0005 #ifndef INCLUDE_V8_PRIMITIVE_H_
0006 #define INCLUDE_V8_PRIMITIVE_H_
0007 
0008 #include "v8-data.h"          // NOLINT(build/include_directory)
0009 #include "v8-internal.h"      // NOLINT(build/include_directory)
0010 #include "v8-local-handle.h"  // NOLINT(build/include_directory)
0011 #include "v8-value.h"         // NOLINT(build/include_directory)
0012 #include "v8config.h"         // NOLINT(build/include_directory)
0013 
0014 namespace v8 {
0015 
0016 class Context;
0017 class Isolate;
0018 class String;
0019 
0020 namespace internal {
0021 class ExternalString;
0022 class ScopedExternalStringLock;
0023 class StringForwardingTable;
0024 }  // namespace internal
0025 
0026 /**
0027  * The superclass of primitive values.  See ECMA-262 4.3.2.
0028  */
0029 class V8_EXPORT Primitive : public Value {};
0030 
0031 /**
0032  * A primitive boolean value (ECMA-262, 4.3.14).  Either the true
0033  * or false value.
0034  */
0035 class V8_EXPORT Boolean : public Primitive {
0036  public:
0037   bool Value() const;
0038   V8_INLINE static Boolean* Cast(v8::Data* data) {
0039 #ifdef V8_ENABLE_CHECKS
0040     CheckCast(data);
0041 #endif
0042     return static_cast<Boolean*>(data);
0043   }
0044 
0045   V8_INLINE static Local<Boolean> New(Isolate* isolate, bool value);
0046 
0047  private:
0048   static void CheckCast(v8::Data* that);
0049 };
0050 
0051 /**
0052  * An array to hold Primitive values. This is used by the embedder to
0053  * pass host defined options to the ScriptOptions during compilation.
0054  *
0055  * This is passed back to the embedder as part of
0056  * HostImportModuleDynamicallyCallback for module loading.
0057  */
0058 class V8_EXPORT PrimitiveArray : public Data {
0059  public:
0060   static Local<PrimitiveArray> New(Isolate* isolate, int length);
0061   int Length() const;
0062   void Set(Isolate* isolate, int index, Local<Primitive> item);
0063   Local<Primitive> Get(Isolate* isolate, int index);
0064 
0065   V8_INLINE static PrimitiveArray* Cast(Data* data) {
0066 #ifdef V8_ENABLE_CHECKS
0067     CheckCast(data);
0068 #endif
0069     return reinterpret_cast<PrimitiveArray*>(data);
0070   }
0071 
0072  private:
0073   static void CheckCast(Data* obj);
0074 };
0075 
0076 /**
0077  * A superclass for symbols and strings.
0078  */
0079 class V8_EXPORT Name : public Primitive {
0080  public:
0081   /**
0082    * Returns the identity hash for this object. The current implementation
0083    * uses an inline property on the object to store the identity hash.
0084    *
0085    * The return value will never be 0. Also, it is not guaranteed to be
0086    * unique.
0087    */
0088   int GetIdentityHash();
0089 
0090   V8_INLINE static Name* Cast(Data* data) {
0091 #ifdef V8_ENABLE_CHECKS
0092     CheckCast(data);
0093 #endif
0094     return static_cast<Name*>(data);
0095   }
0096 
0097  private:
0098   static void CheckCast(Data* that);
0099 };
0100 
0101 /**
0102  * A flag describing different modes of string creation.
0103  *
0104  * Aside from performance implications there are no differences between the two
0105  * creation modes.
0106  */
0107 enum class NewStringType {
0108   /**
0109    * Create a new string, always allocating new storage memory.
0110    */
0111   kNormal,
0112 
0113   /**
0114    * Acts as a hint that the string should be created in the
0115    * old generation heap space and be deduplicated if an identical string
0116    * already exists.
0117    */
0118   kInternalized
0119 };
0120 
0121 /**
0122  * A JavaScript string value (ECMA-262, 4.3.17).
0123  */
0124 class V8_EXPORT String : public Name {
0125  public:
0126   static constexpr int kMaxLength =
0127       internal::kApiSystemPointerSize == 4 ? (1 << 28) - 16 : (1 << 29) - 24;
0128 
0129   enum Encoding {
0130     UNKNOWN_ENCODING = 0x1,
0131     TWO_BYTE_ENCODING = 0x0,
0132     ONE_BYTE_ENCODING = 0x8
0133   };
0134   /**
0135    * Returns the number of characters (UTF-16 code units) in this string.
0136    */
0137   int Length() const;
0138 
0139   /**
0140    * Returns the number of bytes needed for the Utf8 encoding of this string.
0141    * TODO(http://crbug.com/373485796): rename back to Utf8Length().
0142    */
0143   size_t Utf8LengthV2(Isolate* isolate) const;
0144 
0145   /**
0146    * Returns whether this string is known to contain only one byte data,
0147    * i.e. ISO-8859-1 code points.
0148    * Does not read the string.
0149    * False negatives are possible.
0150    */
0151   bool IsOneByte() const;
0152 
0153   /**
0154    * Returns whether this string contain only one byte data,
0155    * i.e. ISO-8859-1 code points.
0156    * Will read the entire string in some cases.
0157    */
0158   bool ContainsOnlyOneByte() const;
0159 
0160   struct WriteFlags {
0161     enum {
0162       kNone = 0,
0163       // Indicates that the output string should be null-terminated. In that
0164       // case, the output buffer must include sufficient space for the
0165       // additional null character.
0166       kNullTerminate = 1,
0167       // Used by WriteUtf8 to replace orphan surrogate code units with the
0168       // unicode replacement character. Needs to be set to guarantee valid UTF-8
0169       // output.
0170       kReplaceInvalidUtf8 = 2
0171     };
0172   };
0173 
0174   /**
0175    * Write the contents of the string to an external buffer.
0176    *
0177    * Copies length characters into the output buffer starting at offset. The
0178    * output buffer must have sufficient space for all characters and the null
0179    * terminator if null termination is requested through the flags.
0180    *
0181    * \param offset The position within the string at which copying begins.
0182    * \param length The number of characters to copy from the string.
0183    * \param buffer The buffer into which the string will be copied.
0184    * \param flags Various flags that influence the behavior of this operation.
0185    * TODO(http://crbug.com/373485796): rename back to Write() and
0186    * WriteOneByte().
0187    */
0188   void WriteV2(Isolate* isolate, uint32_t offset, uint32_t length,
0189                uint16_t* buffer, int flags = WriteFlags::kNone) const;
0190   void WriteOneByteV2(Isolate* isolate, uint32_t offset, uint32_t length,
0191                       uint8_t* buffer, int flags = WriteFlags::kNone) const;
0192 
0193   /**
0194    * Encode the contents of the string as Utf8 into an external buffer.
0195    *
0196    * Encodes the characters of this string as Utf8 and writes them into the
0197    * output buffer until either all characters were encoded or the buffer is
0198    * full. Will not write partial UTF-8 sequences, preferring to stop before
0199    * the end of the buffer. If null termination is requested, the output buffer
0200    * will always be null terminated even if not all characters fit. In that
0201    * case, the capacity must be at least one. The required size of the output
0202    * buffer can be determined using Utf8LengthV2().
0203    *
0204    * \param buffer The buffer into which the string will be written.
0205    * \param capacity The number of bytes available in the output buffer.
0206    * \param flags Various flags that influence the behavior of this operation.
0207    * \param processed_characters_return The number of processed characters from
0208    * the buffer.
0209    * \return The number of bytes copied to the buffer including the null
0210    * terminator (if written).
0211    * TODO(http://crbug.com/373485796): rename back to WriteUtf8().
0212    */
0213   size_t WriteUtf8V2(Isolate* isolate, char* buffer, size_t capacity,
0214                      int flags = WriteFlags::kNone,
0215                      size_t* processed_characters_return = nullptr) const;
0216 
0217   /**
0218    * A zero length string.
0219    */
0220   V8_INLINE static Local<String> Empty(Isolate* isolate);
0221 
0222   /**
0223    * Returns true if the string is external.
0224    */
0225   bool IsExternal() const;
0226 
0227   /**
0228    * Returns true if the string is both external and two-byte.
0229    */
0230   bool IsExternalTwoByte() const;
0231 
0232   /**
0233    * Returns true if the string is both external and one-byte.
0234    */
0235   bool IsExternalOneByte() const;
0236 
0237   /**
0238    * Returns the internalized string. See `NewStringType::kInternalized` for
0239    * details on internalized strings.
0240    */
0241   Local<String> InternalizeString(Isolate* isolate);
0242 
0243   class V8_EXPORT ExternalStringResourceBase {
0244    public:
0245     virtual ~ExternalStringResourceBase() = default;
0246 
0247     /**
0248      * If a string is cacheable, the value returned by
0249      * ExternalStringResource::data() may be cached, otherwise it is not
0250      * expected to be stable beyond the current top-level task.
0251      */
0252     virtual bool IsCacheable() const { return true; }
0253 
0254     /**
0255      * Internally V8 will call this Unaccount method when the external string
0256      * resource should be unaccounted for. This method can be overridden in
0257      * subclasses to control how allocated external bytes are accounted.
0258      */
0259     virtual void Unaccount(Isolate* isolate) {}
0260 
0261     /**
0262      * Returns an estimate of the memory occupied by this external string, to be
0263      * used by V8 when producing a heap snapshot. If this function returns
0264      * kDefaultMemoryEstimate, then V8 will estimate the external size based on
0265      * the string length. This function should return only memory that is
0266      * uniquely owned by this resource. If the resource has shared ownership of
0267      * a secondary allocation, it can report that memory by implementing
0268      * EstimateSharedMemoryUsage.
0269      */
0270     virtual size_t EstimateMemoryUsage() const {
0271       return kDefaultMemoryEstimate;
0272     }
0273     static constexpr size_t kDefaultMemoryEstimate = static_cast<size_t>(-1);
0274 
0275     class V8_EXPORT SharedMemoryUsageRecorder {
0276      public:
0277       /**
0278        * Record that a shared allocation at the given location has the given
0279        * size.
0280        */
0281       virtual void RecordSharedMemoryUsage(const void* location,
0282                                            size_t size) = 0;
0283     };
0284 
0285     /**
0286      * Estimates memory that this string resource may share with other string
0287      * resources, to be used by V8 when producing a heap snapshot.
0288      */
0289     virtual void EstimateSharedMemoryUsage(
0290         SharedMemoryUsageRecorder* recorder) const {}
0291 
0292     // Disallow copying and assigning.
0293     ExternalStringResourceBase(const ExternalStringResourceBase&) = delete;
0294     void operator=(const ExternalStringResourceBase&) = delete;
0295 
0296    protected:
0297     ExternalStringResourceBase() = default;
0298 
0299     /**
0300      * Internally V8 will call this Dispose method when the external string
0301      * resource is no longer needed. The default implementation will use the
0302      * delete operator. This method can be overridden in subclasses to
0303      * control how allocated external string resources are disposed.
0304      */
0305     virtual void Dispose() { delete this; }
0306 
0307     /**
0308      * For a non-cacheable string, the value returned by
0309      * |ExternalStringResource::data()| has to be stable between |Lock()| and
0310      * |Unlock()|, that is the string must behave as is |IsCacheable()| returned
0311      * true.
0312      *
0313      * These two functions must be thread-safe, and can be called from anywhere.
0314      * They also must handle lock depth, in the sense that each can be called
0315      * several times, from different threads, and unlocking should only happen
0316      * when the balance of Lock() and Unlock() calls is 0.
0317      */
0318     virtual void Lock() const {}
0319 
0320     /**
0321      * Unlocks the string.
0322      */
0323     virtual void Unlock() const {}
0324 
0325    private:
0326     friend class internal::ExternalString;
0327     friend class v8::String;
0328     friend class internal::StringForwardingTable;
0329     friend class internal::ScopedExternalStringLock;
0330   };
0331 
0332   /**
0333    * An ExternalStringResource is a wrapper around a two-byte string
0334    * buffer that resides outside V8's heap. Implement an
0335    * ExternalStringResource to manage the life cycle of the underlying
0336    * buffer.  Note that the string data must be immutable.
0337    */
0338   class V8_EXPORT ExternalStringResource : public ExternalStringResourceBase {
0339    public:
0340     /**
0341      * Override the destructor to manage the life cycle of the underlying
0342      * buffer.
0343      */
0344     ~ExternalStringResource() override = default;
0345 
0346     /**
0347      * The string data from the underlying buffer. If the resource is cacheable
0348      * then data() must return the same value for all invocations.
0349      */
0350     virtual const uint16_t* data() const = 0;
0351 
0352     /**
0353      * The length of the string. That is, the number of two-byte characters.
0354      */
0355     virtual size_t length() const = 0;
0356 
0357     /**
0358      * Returns the cached data from the underlying buffer. This method can be
0359      * called only for cacheable resources (i.e. IsCacheable() == true) and only
0360      * after UpdateDataCache() was called.
0361      */
0362     const uint16_t* cached_data() const {
0363       CheckCachedDataInvariants();
0364       return cached_data_;
0365     }
0366 
0367     /**
0368      * Update {cached_data_} with the data from the underlying buffer. This can
0369      * be called only for cacheable resources.
0370      */
0371     void UpdateDataCache();
0372 
0373    protected:
0374     ExternalStringResource() = default;
0375 
0376    private:
0377     void CheckCachedDataInvariants() const;
0378 
0379     const uint16_t* cached_data_ = nullptr;
0380   };
0381 
0382   /**
0383    * An ExternalOneByteStringResource is a wrapper around an one-byte
0384    * string buffer that resides outside V8's heap. Implement an
0385    * ExternalOneByteStringResource to manage the life cycle of the
0386    * underlying buffer.  Note that the string data must be immutable
0387    * and that the data must be Latin-1 and not UTF-8, which would require
0388    * special treatment internally in the engine and do not allow efficient
0389    * indexing.  Use String::New or convert to 16 bit data for non-Latin1.
0390    */
0391 
0392   class V8_EXPORT ExternalOneByteStringResource
0393       : public ExternalStringResourceBase {
0394    public:
0395     /**
0396      * Override the destructor to manage the life cycle of the underlying
0397      * buffer.
0398      */
0399     ~ExternalOneByteStringResource() override = default;
0400 
0401     /**
0402      * The string data from the underlying buffer. If the resource is cacheable
0403      * then data() must return the same value for all invocations.
0404      */
0405     virtual const char* data() const = 0;
0406 
0407     /** The number of Latin-1 characters in the string.*/
0408     virtual size_t length() const = 0;
0409 
0410     /**
0411      * Returns the cached data from the underlying buffer. If the resource is
0412      * uncacheable or if UpdateDataCache() was not called before, it has
0413      * undefined behaviour.
0414      */
0415     const char* cached_data() const {
0416       CheckCachedDataInvariants();
0417       return cached_data_;
0418     }
0419 
0420     /**
0421      * Update {cached_data_} with the data from the underlying buffer. This can
0422      * be called only for cacheable resources.
0423      */
0424     void UpdateDataCache();
0425 
0426    protected:
0427     ExternalOneByteStringResource() = default;
0428 
0429    private:
0430     void CheckCachedDataInvariants() const;
0431 
0432     const char* cached_data_ = nullptr;
0433   };
0434 
0435   /**
0436    * If the string is an external string, return the ExternalStringResourceBase
0437    * regardless of the encoding, otherwise return NULL.  The encoding of the
0438    * string is returned in encoding_out.
0439    */
0440   V8_INLINE ExternalStringResourceBase* GetExternalStringResourceBase(
0441       v8::Isolate* isolate, Encoding* encoding_out) const;
0442   V8_INLINE ExternalStringResourceBase* GetExternalStringResourceBase(
0443       Encoding* encoding_out) const;
0444 
0445   /**
0446    * Get the ExternalStringResource for an external string.  Returns
0447    * NULL if IsExternal() doesn't return true.
0448    */
0449   V8_INLINE ExternalStringResource* GetExternalStringResource() const;
0450 
0451   /**
0452    * Get the ExternalOneByteStringResource for an external one-byte string.
0453    * Returns NULL if IsExternalOneByte() doesn't return true.
0454    */
0455   const ExternalOneByteStringResource* GetExternalOneByteStringResource() const;
0456 
0457   V8_INLINE static String* Cast(v8::Data* data) {
0458 #ifdef V8_ENABLE_CHECKS
0459     CheckCast(data);
0460 #endif
0461     return static_cast<String*>(data);
0462   }
0463 
0464   /**
0465    * Allocates a new string from a UTF-8 literal. This is equivalent to calling
0466    * String::NewFromUtf(isolate, "...").ToLocalChecked(), but without the check
0467    * overhead.
0468    *
0469    * When called on a string literal containing '\0', the inferred length is the
0470    * length of the input array minus 1 (for the final '\0') and not the value
0471    * returned by strlen.
0472    **/
0473   template <int N>
0474   static V8_WARN_UNUSED_RESULT Local<String> NewFromUtf8Literal(
0475       Isolate* isolate, const char (&literal)[N],
0476       NewStringType type = NewStringType::kNormal) {
0477     static_assert(N <= kMaxLength, "String is too long");
0478     return NewFromUtf8Literal(isolate, literal, type, N - 1);
0479   }
0480 
0481   /** Allocates a new string from UTF-8 data. Only returns an empty value when
0482    * length > kMaxLength. **/
0483   static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromUtf8(
0484       Isolate* isolate, const char* data,
0485       NewStringType type = NewStringType::kNormal, int length = -1);
0486 
0487   /** Allocates a new string from Latin-1 data.  Only returns an empty value
0488    * when length > kMaxLength. **/
0489   static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromOneByte(
0490       Isolate* isolate, const uint8_t* data,
0491       NewStringType type = NewStringType::kNormal, int length = -1);
0492 
0493   /** Allocates a new string from UTF-16 data. Only returns an empty value when
0494    * length > kMaxLength. **/
0495   static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromTwoByte(
0496       Isolate* isolate, const uint16_t* data,
0497       NewStringType type = NewStringType::kNormal, int length = -1);
0498 
0499   /**
0500    * Creates a new string by concatenating the left and the right strings
0501    * passed in as parameters.
0502    */
0503   static Local<String> Concat(Isolate* isolate, Local<String> left,
0504                               Local<String> right);
0505 
0506   /**
0507    * Creates a new external string using the data defined in the given
0508    * resource. When the external string is no longer live on V8's heap the
0509    * resource will be disposed by calling its Dispose method. The caller of
0510    * this function should not otherwise delete or modify the resource. Neither
0511    * should the underlying buffer be deallocated or modified except through the
0512    * destructor of the external string resource.
0513    */
0514   static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewExternalTwoByte(
0515       Isolate* isolate, ExternalStringResource* resource);
0516 
0517   /**
0518    * Associate an external string resource with this string by transforming it
0519    * in place so that existing references to this string in the JavaScript heap
0520    * will use the external string resource. The external string resource's
0521    * character contents need to be equivalent to this string.
0522    * Returns true if the string has been changed to be an external string.
0523    * The string is not modified if the operation fails. See NewExternal for
0524    * information on the lifetime of the resource.
0525    */
0526   V8_DEPRECATE_SOON("Use the version with the isolate argument instead.")
0527   bool MakeExternal(ExternalStringResource* resource);
0528 
0529   /**
0530    * Associate an external string resource with this string by transforming it
0531    * in place so that existing references to this string in the JavaScript heap
0532    * will use the external string resource. The external string resource's
0533    * character contents need to be equivalent to this string.
0534    * Returns true if the string has been changed to be an external string.
0535    * The string is not modified if the operation fails. See NewExternal for
0536    * information on the lifetime of the resource.
0537    */
0538   bool MakeExternal(Isolate* isolate, ExternalStringResource* resource);
0539 
0540   /**
0541    * Creates a new external string using the one-byte data defined in the given
0542    * resource. When the external string is no longer live on V8's heap the
0543    * resource will be disposed by calling its Dispose method. The caller of
0544    * this function should not otherwise delete or modify the resource. Neither
0545    * should the underlying buffer be deallocated or modified except through the
0546    * destructor of the external string resource.
0547    */
0548   static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewExternalOneByte(
0549       Isolate* isolate, ExternalOneByteStringResource* resource);
0550 
0551   /**
0552    * Associate an external string resource with this string by transforming it
0553    * in place so that existing references to this string in the JavaScript heap
0554    * will use the external string resource. The external string resource's
0555    * character contents need to be equivalent to this string.
0556    * Returns true if the string has been changed to be an external string.
0557    * The string is not modified if the operation fails. See NewExternal for
0558    * information on the lifetime of the resource.
0559    */
0560   V8_DEPRECATE_SOON("Use the version with the isolate argument instead.")
0561   bool MakeExternal(ExternalOneByteStringResource* resource);
0562 
0563   /**
0564    * Associate an external string resource with this string by transforming it
0565    * in place so that existing references to this string in the JavaScript heap
0566    * will use the external string resource. The external string resource's
0567    * character contents need to be equivalent to this string.
0568    * Returns true if the string has been changed to be an external string.
0569    * The string is not modified if the operation fails. See NewExternal for
0570    * information on the lifetime of the resource.
0571    */
0572   bool MakeExternal(Isolate* isolate, ExternalOneByteStringResource* resource);
0573 
0574   /**
0575    * Returns true if this string can be made external, given the encoding for
0576    * the external string resource.
0577    */
0578   bool CanMakeExternal(Encoding encoding) const;
0579 
0580   /**
0581    * Returns true if the strings values are equal. Same as JS ==/===.
0582    */
0583   bool StringEquals(Local<String> str) const;
0584 
0585   /**
0586    * Converts an object to a null-terminated UTF-8-encoded character array.
0587    * Useful if you want to print the object.  If conversion to a string fails
0588    * (e.g. due to an exception in the toString() method of the object) then the
0589    * length() method returns 0 and the * operator returns NULL.
0590    *
0591    * WARNING: This will unconditionally copy the contents of the JavaScript
0592    * string, and should be avoided in situations where performance is a concern.
0593    * Consider using WriteUtf8() instead.
0594    */
0595   class V8_EXPORT Utf8Value {
0596    public:
0597     Utf8Value(Isolate* isolate, Local<v8::Value> obj);
0598     ~Utf8Value();
0599     char* operator*() { return str_; }
0600     const char* operator*() const { return str_; }
0601     size_t length() const { return length_; }
0602 
0603     // Disallow copying and assigning.
0604     Utf8Value(const Utf8Value&) = delete;
0605     void operator=(const Utf8Value&) = delete;
0606 
0607    private:
0608     char* str_;
0609     size_t length_;
0610   };
0611 
0612   /**
0613    * Converts an object to a two-byte (UTF-16-encoded) string.
0614    *
0615    * If conversion to a string fails (eg. due to an exception in the toString()
0616    * method of the object) then the length() method returns 0 and the * operator
0617    * returns NULL.
0618    *
0619    * WARNING: This will unconditionally copy the contents of the JavaScript
0620    * string, and should be avoided in situations where performance is a concern.
0621    */
0622   class V8_EXPORT Value {
0623    public:
0624     V8_DEPRECATE_SOON(
0625         "Prefer using String::ValueView if you can, or string->Write to a "
0626         "buffer if you cannot.")
0627     Value(Isolate* isolate, Local<v8::Value> obj);
0628     ~Value();
0629     uint16_t* operator*() { return str_; }
0630     const uint16_t* operator*() const { return str_; }
0631     uint32_t length() const { return length_; }
0632 
0633     // Disallow copying and assigning.
0634     Value(const Value&) = delete;
0635     void operator=(const Value&) = delete;
0636 
0637    private:
0638     uint16_t* str_;
0639     uint32_t length_;
0640   };
0641 
0642   /**
0643    * Returns a view onto a string's contents.
0644    *
0645    * WARNING: This does not copy the string's contents, and will therefore be
0646    * invalidated if the GC can move the string while the ValueView is alive. It
0647    * is therefore required that no GC or allocation can happen while there is an
0648    * active ValueView. This requirement may be relaxed in the future.
0649    *
0650    * V8 strings are either encoded as one-byte or two-bytes per character.
0651    */
0652   class V8_EXPORT ValueView {
0653    public:
0654     ValueView(Isolate* isolate, Local<v8::String> str);
0655     ~ValueView();
0656     const uint8_t* data8() const {
0657 #if V8_ENABLE_CHECKS
0658       CheckOneByte(true);
0659 #endif
0660       return data8_;
0661     }
0662     const uint16_t* data16() const {
0663 #if V8_ENABLE_CHECKS
0664       CheckOneByte(false);
0665 #endif
0666       return data16_;
0667     }
0668     uint32_t length() const { return length_; }
0669     bool is_one_byte() const { return is_one_byte_; }
0670 
0671     // Disallow copying and assigning.
0672     ValueView(const ValueView&) = delete;
0673     void operator=(const ValueView&) = delete;
0674 
0675    private:
0676     void CheckOneByte(bool is_one_byte) const;
0677 
0678     Local<v8::String> flat_str_;
0679     union {
0680       const uint8_t* data8_;
0681       const uint16_t* data16_;
0682     };
0683     uint32_t length_;
0684     bool is_one_byte_;
0685     // Avoid exposing the internal DisallowGarbageCollection scope.
0686     alignas(internal::Internals::
0687                 kDisallowGarbageCollectionAlign) char no_gc_debug_scope_
0688         [internal::Internals::kDisallowGarbageCollectionSize];
0689   };
0690 
0691  private:
0692   void VerifyExternalStringResourceBase(ExternalStringResourceBase* v,
0693                                         Encoding encoding) const;
0694   void VerifyExternalStringResource(ExternalStringResource* val) const;
0695   ExternalStringResource* GetExternalStringResourceSlow() const;
0696   ExternalStringResourceBase* GetExternalStringResourceBaseSlow(
0697       String::Encoding* encoding_out) const;
0698 
0699   static Local<v8::String> NewFromUtf8Literal(Isolate* isolate,
0700                                               const char* literal,
0701                                               NewStringType type, int length);
0702 
0703   static void CheckCast(v8::Data* that);
0704 };
0705 
0706 // Zero-length string specialization (templated string size includes
0707 // terminator).
0708 template <>
0709 inline V8_WARN_UNUSED_RESULT Local<String> String::NewFromUtf8Literal(
0710     Isolate* isolate, const char (&literal)[1], NewStringType type) {
0711   return String::Empty(isolate);
0712 }
0713 
0714 /**
0715  * Interface for iterating through all external resources in the heap.
0716  */
0717 class V8_EXPORT ExternalResourceVisitor {
0718  public:
0719   virtual ~ExternalResourceVisitor() = default;
0720   virtual void VisitExternalString(Local<String> string) {}
0721 };
0722 
0723 /**
0724  * A JavaScript symbol (ECMA-262 edition 6)
0725  */
0726 class V8_EXPORT Symbol : public Name {
0727  public:
0728   /**
0729    * Returns the description string of the symbol, or undefined if none.
0730    */
0731   Local<Value> Description(Isolate* isolate) const;
0732 
0733   /**
0734    * Create a symbol. If description is not empty, it will be used as the
0735    * description.
0736    */
0737   static Local<Symbol> New(Isolate* isolate,
0738                            Local<String> description = Local<String>());
0739 
0740   /**
0741    * Access global symbol registry.
0742    * Note that symbols created this way are never collected, so
0743    * they should only be used for statically fixed properties.
0744    * Also, there is only one global name space for the descriptions used as
0745    * keys.
0746    * To minimize the potential for clashes, use qualified names as keys.
0747    */
0748   static Local<Symbol> For(Isolate* isolate, Local<String> description);
0749 
0750   /**
0751    * Retrieve a global symbol. Similar to |For|, but using a separate
0752    * registry that is not accessible by (and cannot clash with) JavaScript code.
0753    */
0754   static Local<Symbol> ForApi(Isolate* isolate, Local<String> description);
0755 
0756   // Well-known symbols
0757   static Local<Symbol> GetAsyncIterator(Isolate* isolate);
0758   static Local<Symbol> GetHasInstance(Isolate* isolate);
0759   static Local<Symbol> GetIsConcatSpreadable(Isolate* isolate);
0760   static Local<Symbol> GetIterator(Isolate* isolate);
0761   static Local<Symbol> GetMatch(Isolate* isolate);
0762   static Local<Symbol> GetReplace(Isolate* isolate);
0763   static Local<Symbol> GetSearch(Isolate* isolate);
0764   static Local<Symbol> GetSplit(Isolate* isolate);
0765   static Local<Symbol> GetToPrimitive(Isolate* isolate);
0766   static Local<Symbol> GetToStringTag(Isolate* isolate);
0767   static Local<Symbol> GetUnscopables(Isolate* isolate);
0768   static Local<Symbol> GetDispose(Isolate* isolate);
0769   static Local<Symbol> GetAsyncDispose(Isolate* isolate);
0770 
0771   V8_INLINE static Symbol* Cast(Data* data) {
0772 #ifdef V8_ENABLE_CHECKS
0773     CheckCast(data);
0774 #endif
0775     return static_cast<Symbol*>(data);
0776   }
0777 
0778  private:
0779   Symbol();
0780   static void CheckCast(Data* that);
0781 };
0782 
0783 /**
0784  * A JavaScript numeric value (either Number or BigInt).
0785  * https://tc39.es/ecma262/#sec-numeric-types
0786  */
0787 class V8_EXPORT Numeric : public Primitive {
0788  private:
0789   Numeric();
0790   static void CheckCast(v8::Data* that);
0791 };
0792 
0793 /**
0794  * A JavaScript number value (ECMA-262, 4.3.20)
0795  */
0796 class V8_EXPORT Number : public Numeric {
0797  public:
0798   double Value() const;
0799   static Local<Number> New(Isolate* isolate, double value);
0800   template <typename Int>
0801     requires(std::is_integral<Int>::value && !std::is_same<Int, bool>::value &&
0802              std::is_signed_v<Int> && sizeof(Int) <= sizeof(int32_t))
0803   V8_INLINE static Local<Number> New(Isolate* isolate, Int value) {
0804     return NewFromInt32(isolate, value);
0805   }
0806   template <typename UInt>
0807     requires(std::is_integral<UInt>::value &&
0808              !std::is_same<UInt, bool>::value && std::is_unsigned_v<UInt> &&
0809              sizeof(UInt) <= sizeof(uint32_t))
0810   V8_INLINE static Local<Number> New(Isolate* isolate, UInt value) {
0811     return NewFromUint32(isolate, value);
0812   }
0813   V8_INLINE static Number* Cast(v8::Data* data) {
0814 #ifdef V8_ENABLE_CHECKS
0815     CheckCast(data);
0816 #endif
0817     return static_cast<Number*>(data);
0818   }
0819 
0820  private:
0821   Number();
0822   static Local<Number> NewFromInt32(Isolate* isolate, int32_t value);
0823   static Local<Number> NewFromUint32(Isolate* isolate, uint32_t value);
0824   static void CheckCast(v8::Data* that);
0825 };
0826 
0827 /**
0828  * A JavaScript value representing a signed integer.
0829  */
0830 class V8_EXPORT Integer : public Number {
0831  public:
0832   static Local<Integer> New(Isolate* isolate, int32_t value);
0833   static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value);
0834   int64_t Value() const;
0835   V8_INLINE static Integer* Cast(v8::Data* data) {
0836 #ifdef V8_ENABLE_CHECKS
0837     CheckCast(data);
0838 #endif
0839     return static_cast<Integer*>(data);
0840   }
0841 
0842  private:
0843   Integer();
0844   static void CheckCast(v8::Data* that);
0845 };
0846 
0847 /**
0848  * A JavaScript value representing a 32-bit signed integer.
0849  */
0850 class V8_EXPORT Int32 : public Integer {
0851  public:
0852   int32_t Value() const;
0853   V8_INLINE static Int32* Cast(v8::Data* data) {
0854 #ifdef V8_ENABLE_CHECKS
0855     CheckCast(data);
0856 #endif
0857     return static_cast<Int32*>(data);
0858   }
0859 
0860  private:
0861   Int32();
0862   static void CheckCast(v8::Data* that);
0863 };
0864 
0865 /**
0866  * A JavaScript value representing a 32-bit unsigned integer.
0867  */
0868 class V8_EXPORT Uint32 : public Integer {
0869  public:
0870   uint32_t Value() const;
0871   V8_INLINE static Uint32* Cast(v8::Data* data) {
0872 #ifdef V8_ENABLE_CHECKS
0873     CheckCast(data);
0874 #endif
0875     return static_cast<Uint32*>(data);
0876   }
0877 
0878  private:
0879   Uint32();
0880   static void CheckCast(v8::Data* that);
0881 };
0882 
0883 /**
0884  * A JavaScript BigInt value (https://tc39.github.io/proposal-bigint)
0885  */
0886 class V8_EXPORT BigInt : public Numeric {
0887  public:
0888   static Local<BigInt> New(Isolate* isolate, int64_t value);
0889   static Local<BigInt> NewFromUnsigned(Isolate* isolate, uint64_t value);
0890   /**
0891    * Creates a new BigInt object using a specified sign bit and a
0892    * specified list of digits/words.
0893    * The resulting number is calculated as:
0894    *
0895    * (-1)^sign_bit * (words[0] * (2^64)^0 + words[1] * (2^64)^1 + ...)
0896    */
0897   static MaybeLocal<BigInt> NewFromWords(Local<Context> context, int sign_bit,
0898                                          int word_count, const uint64_t* words);
0899 
0900   /**
0901    * Returns the value of this BigInt as an unsigned 64-bit integer.
0902    * If `lossless` is provided, it will reflect whether the return value was
0903    * truncated or wrapped around. In particular, it is set to `false` if this
0904    * BigInt is negative.
0905    */
0906   uint64_t Uint64Value(bool* lossless = nullptr) const;
0907 
0908   /**
0909    * Returns the value of this BigInt as a signed 64-bit integer.
0910    * If `lossless` is provided, it will reflect whether this BigInt was
0911    * truncated or not.
0912    */
0913   int64_t Int64Value(bool* lossless = nullptr) const;
0914 
0915   /**
0916    * Returns the number of 64-bit words needed to store the result of
0917    * ToWordsArray().
0918    */
0919   int WordCount() const;
0920 
0921   /**
0922    * Writes the contents of this BigInt to a specified memory location.
0923    * `sign_bit` must be provided and will be set to 1 if this BigInt is
0924    * negative.
0925    * `*word_count` has to be initialized to the length of the `words` array.
0926    * Upon return, it will be set to the actual number of words that would
0927    * be needed to store this BigInt (i.e. the return value of `WordCount()`).
0928    */
0929   void ToWordsArray(int* sign_bit, int* word_count, uint64_t* words) const;
0930 
0931   V8_INLINE static BigInt* Cast(v8::Data* data) {
0932 #ifdef V8_ENABLE_CHECKS
0933     CheckCast(data);
0934 #endif
0935     return static_cast<BigInt*>(data);
0936   }
0937 
0938  private:
0939   BigInt();
0940   static void CheckCast(v8::Data* that);
0941 };
0942 
0943 Local<String> String::Empty(Isolate* isolate) {
0944   using S = internal::Address;
0945   using I = internal::Internals;
0946   I::CheckInitialized(isolate);
0947   S* slot = I::GetRootSlot(isolate, I::kEmptyStringRootIndex);
0948   return Local<String>::FromSlot(slot);
0949 }
0950 
0951 String::ExternalStringResource* String::GetExternalStringResource() const {
0952   using A = internal::Address;
0953   using I = internal::Internals;
0954   A obj = internal::ValueHelper::ValueAsAddress(this);
0955 
0956   ExternalStringResource* result;
0957   if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
0958     Isolate* isolate = I::GetCurrentIsolateForSandbox();
0959     A value = I::ReadExternalPointerField<internal::kExternalStringResourceTag>(
0960         isolate, obj, I::kStringResourceOffset);
0961     result = reinterpret_cast<String::ExternalStringResource*>(value);
0962   } else {
0963     result = GetExternalStringResourceSlow();
0964   }
0965 #ifdef V8_ENABLE_CHECKS
0966   VerifyExternalStringResource(result);
0967 #endif
0968   return result;
0969 }
0970 
0971 String::ExternalStringResourceBase* String::GetExternalStringResourceBase(
0972     v8::Isolate* isolate, String::Encoding* encoding_out) const {
0973   using A = internal::Address;
0974   using I = internal::Internals;
0975   A obj = internal::ValueHelper::ValueAsAddress(this);
0976   int type = I::GetInstanceType(obj) & I::kStringRepresentationAndEncodingMask;
0977   *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
0978   ExternalStringResourceBase* resource;
0979   if (type == I::kExternalOneByteRepresentationTag ||
0980       type == I::kExternalTwoByteRepresentationTag) {
0981     A value = I::ReadExternalPointerField<internal::kExternalStringResourceTag>(
0982         isolate, obj, I::kStringResourceOffset);
0983     resource = reinterpret_cast<ExternalStringResourceBase*>(value);
0984   } else {
0985     resource = GetExternalStringResourceBaseSlow(encoding_out);
0986   }
0987 #ifdef V8_ENABLE_CHECKS
0988   VerifyExternalStringResourceBase(resource, *encoding_out);
0989 #endif
0990   return resource;
0991 }
0992 
0993 String::ExternalStringResourceBase* String::GetExternalStringResourceBase(
0994     String::Encoding* encoding_out) const {
0995   using A = internal::Address;
0996   using I = internal::Internals;
0997   A obj = internal::ValueHelper::ValueAsAddress(this);
0998   int type = I::GetInstanceType(obj) & I::kStringRepresentationAndEncodingMask;
0999   *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
1000   ExternalStringResourceBase* resource;
1001   if (type == I::kExternalOneByteRepresentationTag ||
1002       type == I::kExternalTwoByteRepresentationTag) {
1003     Isolate* isolate = I::GetCurrentIsolateForSandbox();
1004     A value = I::ReadExternalPointerField<internal::kExternalStringResourceTag>(
1005         isolate, obj, I::kStringResourceOffset);
1006     resource = reinterpret_cast<ExternalStringResourceBase*>(value);
1007   } else {
1008     resource = GetExternalStringResourceBaseSlow(encoding_out);
1009   }
1010 #ifdef V8_ENABLE_CHECKS
1011   VerifyExternalStringResourceBase(resource, *encoding_out);
1012 #endif
1013   return resource;
1014 }
1015 
1016 // --- Statics ---
1017 
1018 V8_INLINE Local<Primitive> Undefined(Isolate* isolate) {
1019   using S = internal::Address;
1020   using I = internal::Internals;
1021   I::CheckInitialized(isolate);
1022   S* slot = I::GetRootSlot(isolate, I::kUndefinedValueRootIndex);
1023   return Local<Primitive>::FromSlot(slot);
1024 }
1025 
1026 V8_INLINE Local<Primitive> Null(Isolate* isolate) {
1027   using S = internal::Address;
1028   using I = internal::Internals;
1029   I::CheckInitialized(isolate);
1030   S* slot = I::GetRootSlot(isolate, I::kNullValueRootIndex);
1031   return Local<Primitive>::FromSlot(slot);
1032 }
1033 
1034 V8_INLINE Local<Boolean> True(Isolate* isolate) {
1035   using S = internal::Address;
1036   using I = internal::Internals;
1037   I::CheckInitialized(isolate);
1038   S* slot = I::GetRootSlot(isolate, I::kTrueValueRootIndex);
1039   return Local<Boolean>::FromSlot(slot);
1040 }
1041 
1042 V8_INLINE Local<Boolean> False(Isolate* isolate) {
1043   using S = internal::Address;
1044   using I = internal::Internals;
1045   I::CheckInitialized(isolate);
1046   S* slot = I::GetRootSlot(isolate, I::kFalseValueRootIndex);
1047   return Local<Boolean>::FromSlot(slot);
1048 }
1049 
1050 Local<Boolean> Boolean::New(Isolate* isolate, bool value) {
1051   return value ? True(isolate) : False(isolate);
1052 }
1053 
1054 }  // namespace v8
1055 
1056 #endif  // INCLUDE_V8_PRIMITIVE_H_